java iText 直接打印

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29755305/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 15:51:51  来源:igfitidea点击:

iText direct Printing

javapdfprintingitext

提问by fareed

I am using iText to generate a pdf and write it to the file system as the following:

我正在使用 iText 生成 pdf 并将其写入文件系统,如下所示:

private void createPDF() throws Exception{
    com.itextpdf.text.Document doc = new com.itextpdf.text.Document();
    PdfWriter docWriter = null;
    path = "C:\PATH\TO\Desktop\EXAMPLE_FOLDER\" + pdfFilename;
    docWriter = PdfWriter.getInstance(doc, new FileOutputStream(path));
    doc.addTitle("Invoice");
    doc.setPageSize(PageSize.A4);
    doc.open();
    PdfContentByte cb = docWriter.getDirectContent();
    fillPDFDetails(cb);
    if (doc != null) {
        doc.close();
    }
    if (docWriter != null) {
        docWriter.close();
    }
}

However, I want to send the pdf to the printer and print the pdf file instead of writing it to the file system. How can I achieve this?

但是,我想将 pdf 发送到打印机并打印 pdf 文件,而不是将其写入文件系统。我怎样才能做到这一点?

回答by Bruno Lowagie

There's a theoretical and a practical answer to this question.

这个问题有一个理论上的和一个实际的答案。

Let's start with the theoretical answer. There's a Java class called PrintStreamthat allows you to send an OutputStreamto a printer:

让我们从理论上的答案开始。有一个 Java 类被调用PrintStream,它允许您将一个发送OutputStream到打印机:

Printstreamextends FilterOutputStreamextends OutputStream

A PrintStreamadds functionality to another output stream, namely the ability to print representations of various data values conveniently. Two other features are provided as well. Unlike other output streams, a PrintStreamnever throws an IOException; instead, exceptional situations merely set an internal flag that can be tested via the checkErrormethod. Optionally, a PrintStreamcan be created so as to flush automatically; this means that the flush method is automatically invoked after a byte array is written, one of the println methods is invoked, or a newline character or byte ('\n') is written.

Printstream延伸FilterOutputStream延伸OutputStream

APrintStream向另一个输出流添加功能,即方便地打印各种数据值的表示的能力。还提供了另外两个功能。与其他输出流不同,aPrintStream从不抛出IOException; 相反,异常情况仅设置一个可以通过该checkError方法进行测试的内部标志 。可选地,PrintStream可以创建 a 以便自动刷新;这意味着在写入字节数组、调用 println 方法之一或'\n'写入换行符或字节 ( )后,会自动调用刷新方法。

So, suppose that you would like to create a PDF in memory and write it to a printer, you'd do something like this:

因此,假设您想在内存中创建一个 PDF 并将其写入打印机,您可以执行以下操作:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(baos);
Document document = new Document();
PdfWriter.getInstance(document, ps);
document.open();
// add content
document.close();

As PrintStreamextends OutputStreamand as PdfWriteraccepts any type of OutputStream, you are writing the PDF bytes to the printer and if you want the PDF bytes, you can do baos.toByteArray().

作为PrintStream扩展OutputStreamPdfWriter接受任何类型的OutputStream,您正在将 PDF 字节写入打印机,如果您想要 PDF 字节,您可以执行baos.toByteArray().

However, the code snippet above sends PDF bytes to the printer. Chances are that your printer doesn't understand PDF and just prints out stuff like:

但是,上面的代码段将 PDF 字节发送到打印机。很有可能您的打印机不理解 PDF,只是打印出以下内容:

PDF-1.4
%a??ó
2 0 obj
<</Length 64/Filter/FlateDecode>>stream
*binary stuff*
endstream
endobj
4 0 obj
<</Parent 3 0 R/Contents 2 0 R/Type/Page/Resources<</Font<</F1 1 0 R>>>>
/MediaBox[0 0 595 842]>>
endobj
1 0 obj
<</BaseFont/Helvetica/Type/Font/Encoding/WinAnsiEncoding/Subtype/Type1>>
endobj
3 0 obj
<</Type/Pages/Count 1/Kids[4 0 R]>>
endobj
5 0 obj
<</Type/Catalog/Pages 3 0 R>>
endobj
6 0 obj
<</Producer(iText? 5.4.2 ?2000-2012 1T3XT BVBA \(AGPL-version\))
/ModDate(D:20130502165150+02'00')/CreationDate(D:20130502165150+02'00')>>
endobj
xref
0 7
0000000000 65535 f 
0000000302 00000 n 
0000000015 00000 n 
0000000390 00000 n 
0000000145 00000 n 
0000000441 00000 n 
0000000486 00000 n 
trailer
<</Root 5 0 R/ID [<91bee3a87061eb2834fb6a3258bf817e><91bee3a87061eb2834fb6a3258bf817e>]
/Info 6 0 R/Size 7>>
%iText-5.4.2
startxref
639
%%EOF

Update:

更新:

In a comment, the following link was added: https://blog.idrsolutions.com/2010/01/printing-pdf-files-from-java/

在评论中,添加了以下链接:https: //blog.idrsolutions.com/2010/01/printing-pdf-files-from-java/

This is actually a better way to print your file:

这实际上是打印文件的更好方法:

FileInputStream fis = new FileInputStream(“C:/mypdf.pdf”);
Doc pdfDoc = new SimpleDoc(fis, null, null);
DocPrintJob printJob = printService.createPrintJob();
printJob.print(pdfDoc, new HashPrintRequestAttributeSet());
fis.close();

If you don't want to use a FileInputStream, you can always create the PDF as a ByteArrayOutputStreamand use the resulting byte[]to create a ByteArrayInputStream.

如果您不想使用FileInputStream,您始终可以将 PDF 创建为 aByteArrayOutputStream并使用结果byte[]创建ByteArrayInputStream.

That's what the practical answer is about: it's not that difficult to create a PDF in memory. That's done like this:

这就是实际答案的内容:在内存中创建 PDF 并不难。这样做是这样的:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
Document document = new Document();
PdfWriter.getInstance(document, baos);
document.open();
// add content
document.close();
byte[] pdf = baos.toByteArray();

The question is: what are you going to do with pdf?

问题是:你打算怎么办pdf

Either your printer understands those bytes (there are printers that accept PDF syntax), or you'll have to find software that converts PDF into a format that printers understand. Usually, people use PDF rendering software (such as Adobe Reader) to print a document. Many of these viewers (Adobe Reader is one of them), require the file to exist as a file: Adobe Reader does not accept a byte array.

您的打印机可以理解这些字节(有些打印机可以接受 PDF 语法),或者您必须找到将 PDF 转换为打印机可以理解的格式的软件。通常,人们使用 PDF 渲染软件(例如 Adob​​e Reader)来打印文档。许多这些查看器(Adobe Reader 就是其中之一)要求文件作为文件存在:Adobe Reader 不接受字节数组。

This explains why the practical answer isn't as easy as the theoretical answer: in practice, your question is far from trivial: it depends on the printer (which formats does it accept) and the PDF viewer (should you require one).

这解释了为什么实际答案不像理论答案那么简单:在实践中,您的问题远非微不足道:它取决于打印机(它接受哪种格式)和 PDF 查看器(您是否需要)。

回答by Gerard Martinelli

Try this :

试试这个 :

filename = "aaaaaaa.pdf";
java.io.File fileout =  new File(filename);
com.lowagie.tools.Executable.printDocumentSilent(fileout));
 fileout.delete();  // if you don't want to keep it.