如何直接打印Itext Pdf文件而不是创建一个新文件

时间:2018-12-27 11:15:34

标签: java

我正在尝试使用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();

1 个答案:

答案 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);