2

I'm trying to convert a TIFF to a PDF using Apache Imaging and PDFBox. Everything I've tried results in a blank (but non-zero-byte) pdf.

There are some examples in other SO questions like Add BufferedImage to PDFBox document and PDFBox draw black image from BufferedImage which I've tried.

I know the buffered image that I'm reading from the TIFF is valid because I can display it and see it in a JFrame.

I've also tried a PDFJpeg instead of a PDFPixelMap, and contentStream.drawImage() instead of .drawXObject(), the result is always the same.

I also tried creating the PDXObjectImage before the content stream and writing multiple images as recommended in Can't add an image to a pdf using PDFBox, the result is still the same. The output file is larger when I write the image multiple times, so it's doing "something" but I don't know what it is.

How can I write a BufferedImage to a page on a PDF using PDFBox?

try(PDDocument document = new PDDocument();ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) 
{

    PDPage blankPage = new PDPage();
    document.addPage( blankPage );
  //  PDXObjectImage pdImage = new PDJpeg(document, image);
    PDXObjectImage pdImage = new PDPixelMap(document, image);
  //  contentStream.drawImage(pdImage, 5, 300);
    PDPageContentStream contentStream = new PDPageContentStream(document, blankPage);
    contentStream.drawXObject(pdImage, 5, 5, 100, 100);
    document.save("test.pdf");
    contentStream.close();
}
catch(COSVisitorException ex) {
    throw new IOException(ex);
}
Community
  • 1
  • 1
Jason
  • 7,356
  • 4
  • 41
  • 48
  • You should do `contentStream.close()` before `document.save("test.pdf")` – mkl Oct 02 '15 at 14:01
  • 3
    Possibly duplicate of this? https://stackoverflow.com/questions/31391337/pdf-generated-with-pdfbox-is-blank/31391930#31391930 (you haven't closed your content stream before saving). – Tilman Hausherr Oct 02 '15 at 14:06
  • That was it, thank you! Do you want to put this in an answer and I'll upvote you? – Jason Oct 02 '15 at 14:06
  • It's not an exact duplicate, but is a subset of the same issue. I think it's a distinct question but if you think it's a duplicate I'm ok with close this as a dupe. – Jason Oct 02 '15 at 14:08
  • Bonus hint: download the sources and look for the AddImageToPDF tool. It has a case for TIFF files (but this will only work with G4 compressed TIFFs). It will need jai_imageio (I think). – Tilman Hausherr Oct 02 '15 at 14:13
  • IMO it is a duplicate because your PDF is blank. You can upvote the linked issue if you want :-) – Tilman Hausherr Oct 02 '15 at 14:14

0 Answers0