我正在尝试使用itext 1.3创建文档,我已经将pdftable附加到该文档上,现在我正在尝试打印该文件,而不是下载代码,我正在尝试使用javax.print函数,但是出现错误
我有一些来自stackoverflow和https://www.programcreek.com/java-api-examples/?api=javax.print.SimpleDoc
的示例Document document = new Document();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
document.setPageSize(PageSize.A4);
document.open();
document.add(createFirstTable(this.printData, document));
document.close();
byte[] pdfBytes = baos.toByteArray();
DocFlavor flavor = DocFlavor.BYTE_ARRAY.AUTOSENSE;
PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();
aset.add(MediaSizeName.ISO_A4);
PrintService[] pservices = PrintServiceLookup.lookupPrintServices(flavor, aset);
FileInputStream fis = new FileInputStream(filename);
DocPrintJob job = pservices[0].createPrintJob();
Doc doc = new SimpleDoc(pdfBytes, flavor, null);
job.print(doc, null);
错误:
[12/27/18 16:44:43:820 IST] 0000002d SystemErr R java.lang.ArrayIndexOutOfBoundsException:数组索引超出范围:0
在此行
DocPrintJob job = pservices[0].createPrintJob();
答案 0 :(得分:0)
问题很明显-打印服务列表为空。您永远不要通过硬索引访问它!
System.out.println(Arrays.toString(pservices));
//You should never access it via an hard index!
//DocPrintJob job = pservices[0].createPrintJob();
PrintService[] pservices = PrintServiceLookup.lookupPrintServices(flavor, aset);
if(!pservices.isEmpty()){
FileInputStream fis = new FileInputStream(filename);
DocPrintJob job = pservices[0].createPrintJob();
Doc doc = new SimpleDoc(pdfBytes, flavor, null);
job.print(doc, null);
}
else{
System.err.println("No printer found.");
}
如果您想知道为什么找不到打印机,请尝试不使用AUTOSENSE
约束:
PrintService[] pservices = PrintServiceLookup.lookupPrintServices(null, aset);