How to print a PDF created with iText?

2019-02-25 02:48发布

问题:

Hi I have created a PDF file with an image in it, I want to print my pdf after creating. Better if I have the PDF in memory instead of having a file, and then send it to the printer... Any Idea ?

I am using iText. Check my code:

    import com.lowagie.text.Document;
    import com.lowagie.text.DocumentException;
    import com.lowagie.text.Image;
    import com.lowagie.text.PageSize;
    import com.lowagie.text.Rectangle;
    import com.lowagie.text.pdf.PdfContentByte;
    import com.lowagie.text.pdf.PdfPrinterGraphics2D;
    import com.lowagie.text.pdf.PdfTemplate;
    import com.lowagie.text.pdf.PdfWriter;

    import javax.imageio.ImageIO;

    import java.awt.Color;
    import java.awt.Graphics2D;
    import java.awt.Toolkit;
    import java.awt.image.BufferedImage;
    import java.io.ByteArrayInputStream;
    import java.io.File;
    import java.io.FileOutputStream;
    import java.io.IOException;
    import java.io.InputStream;


        private boolean exportToPdfThroughPNG(String fileName, float width, float height) throws DocumentException, IOException {
        logger.debug("[boolean exportToPdfQuick() throws IOException, DocumentException]");

        BufferedImage pngFile = createPngFile();

        Document document = new Document();
        document.setPageSize(new Rectangle(width, height));
        PdfWriter.getInstance(document, new FileOutputStream(fileName));
        document.open();
        Image image = Image.getInstance(Toolkit.getDefaultToolkit().createImage(pngFile.getSource()), Color.WHITE);
        document.add(image);
        // If some day anyone wants to put text in the pdf. @Eduardo
        // document.add(new Paragraph("title of the process"));
        document.close();

        return true;
    }

Thanks in advance!

回答1:

You can always use a ByteArrayOutputStream instead of a FileOutputStream.

After you have the PDF bytes, its a normal "how do you print in Java" question. Many printers (or at least their drivers) will take PDF directly these days, so at that point one could argue that you're done.

PS: Once I tagged your question "Java" it colored your code block using "import" as a keyword and so forth. Something to keep in mind in the future.