0

I have a generated PDF document using iText library, then I kept the document in memory using a ByteArrayOutputStream to print it but it's not printing anything. Any idea on why isn't it printing? You can find the code below and thanks in advance.

    ByteArrayOutputStream byteArr = new ByteArrayOutputStream();
    Document document = new Document();
    PdfWriter.getInstance(document, byteArr);
    document.open();

    /*
    * Adding data and tables to the document
    */

    document.close();

    DocFlavor docType = DocFlavor.BYTE_ARRAY.AUTOSENSE;    
    byte[] byteStream = byteArr.toByteArray();// fetch content in byte array;
    // byteArr is the ByteArrayOutputStream object
    // Tried using InputStream but did not work as well.

    Doc documentToBePrinted = new SimpleDoc(byteStream, docType, null);
    PrintRequestAttributeSet aset = new HashPrintRequestAttributeSet();  
    PrintService services = PrintServiceLookup.lookupDefaultPrintService();               
    DocPrintJob job = services.createPrintJob();  
    try {  
    job.print(documentToBePrinted, aset);
    System.out.println("Donee");

    } 
    catch (Exception pe)
    {
     pe.printStackTrace();

    } 

    byteArr = null;


}
  • 1
    Your code sample is not self-contained, making it impossible for anyone to debug it, or inspect what is going on. Please edit your post to ensure your code-sample can be inspected and debugged. – Joris Schellekens May 09 '18 at 09:21
  • @JorisSchellekens Thanks for the tip. I updated the code, hope it is clearer now and sorry for not making it so at first. – Mohammed Amer May 09 '18 at 09:42

2 Answers2

1

Without being able to run your code, this is not an easy question to answer.

Possible issue is that you are not closing the PdfDocument class. As a result, the underlying resources are not released, and the bytes are not flushed.

As a result, an invalid (sometimes even empty) PDF document is generated, which of course the printer will not (or can not) print.

If you can store the PDF, and it displays properly in a viewer, then you are most likely doing something wrong in the printing part of the application.

Joris Schellekens
  • 8,483
  • 2
  • 23
  • 54
  • Thanks for your time. I updated the post to be clearer. The document is actually closed before the printing operation. And I tried saving the PDF document and it works fine. I guess I'm just doing something wrong in the printing process. – Mohammed Amer May 09 '18 at 09:44
  • You are sending PDF bytes to a printer, but not all printers understand PDF. If your printer doesn't understand PDF, it won't be able to print the PDF. Usually you need some software able to render PDF in-between your PDF and your printer. – Bruno Lowagie May 09 '18 at 11:07
  • @BrunoLowagie Thanks for your time. You made it very clear, but when I print a normal PDF document using an InputStream object with the document location; it prints properly. So I guess it understands PDF and the problem is in my printing code? – Mohammed Amer May 09 '18 at 11:18
  • OK, that's important information. If you want to know if the PDF generated by iText is causing the problem, save the PDF to a file, open that PDF as an `InputStream` and print it the same way you print "a normal PDF." It it prints just like any other normal PDF, then the problem isn't caused by iText. If it doesn't print, we'll have to examine the PDF. There's a chance that `document.close();` is never reached, e.g. because an exception was thrown. In that case `job.print(documentToBePrinted, aset);` is never reached either, and the document is never printed. – Bruno Lowagie May 09 '18 at 12:20
  • Thank you for your time. I saved the PDF as a file, opened it as an `InputStream` , then tried to print it the way I did before and it also did not print! Kindly note that the printer icon appeared in the task bar showing that there is a document to be printed, also appeared on using `ByteArrayOutputStream` but nothing was printed. – Mohammed Amer May 09 '18 at 13:02
  • Another point, when I saved the generated PDF by iText and ran the printing code using `InputStream` separately on that document, it printed properly and also the printer icon appeared. As it happened earlier. – Mohammed Amer May 09 '18 at 13:25
0

Probably the printer you are using doesn't support PDF directly. Try using PDFBox to print the document. I made a small maven project to test it and it works for me:

Main.java:

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.printing.PDFPageable;

import javax.print.*;
import java.awt.print.PrinterJob;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

class Main {
    public static void main(String[] args) throws DocumentException, IOException {
        ByteArrayOutputStream byteArr = new ByteArrayOutputStream();
        Document pdfDocument = new Document();
        PdfWriter.getInstance(pdfDocument, byteArr);
        pdfDocument.open();
        pdfDocument.add(new Paragraph("Hello World!"));
        pdfDocument.close();

        byte[] byteStream = byteArr.toByteArray();// fetch content in byte array;
        PrintService services = PrintServiceLookup.lookupDefaultPrintService();
        PrinterJob job = PrinterJob.getPrinterJob();
        PDDocument pdDocument = null;
        try {
            pdDocument = PDDocument.load(byteStream);
            job.setPageable(new PDFPageable(pdDocument));
            job.setPrintService(services);
            job.print();
            System.out.println("Done");

        } catch (Exception pe) {
            pe.printStackTrace();

        } finally {
            if (pdDocument != null) {
                pdDocument.close();
            }
        }


    }
}

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>it.fortytwoapps</groupId>
    <artifactId>so-50249273</artifactId>
    <version>1.0-SNAPSHOT</version>
    <dependencies>
        <dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itextpdf</artifactId>
            <version>5.5.13</version>
        </dependency>

        <dependency>
            <groupId>org.apache.pdfbox</groupId>
            <artifactId>pdfbox</artifactId>
            <version>2.0.9</version>
        </dependency>
    </dependencies>
</project>
cerebro84
  • 28
  • 10
  • Thank you so much! been trying to get this work for a week now. And suddenly it seemed so simple.. Thank you for your time. – Mohammed Amer May 13 '18 at 09:55