pdfitextpdfstamper

Errors adding images to pdf using itext 5.5.6 and FullCompression on pdfStamper


Last week we upgrade from itext 5.3.6 to 5.5.6 during our test we detect problems adding images on an existing pdf with full compression enabled. See the next code example:

  try {

    byte[] imageByte = IOUtils.toByteArray(new FileInputStream("imageToStamp.png"));
    InputStream input = new FileInputStream("originalFile.pdf");
    byte[] inputBytes = IOUtils.toByteArray(input);
    OutputStream output = new FileOutputStream("originalFileStamped.pdf");
    PdfReader pdfReader = new PdfReader(new ByteArrayInputStream(inputBytes));
    PdfStamper pdfStamper = new PdfStamper(pdfReader,output);
  Image image = Image.getInstance(imageByte);
  for(int i=1; i<= pdfReader.getNumberOfPages(); i++){
      PdfContentByte content = pdfStamper.getUnderContent(i);
      image.setAbsolutePosition(100f, 700f);
      content.addImage(image);
  }
  //Full Compresión breaks the final pdf , if you comment that line the final PDF will had the images.
  pdfStamper.setFullCompression();
  pdfStamper.close();
} catch (IOException e) {
  e.printStackTrace();
} catch (DocumentException e) {
  e.printStackTrace();
}

If we use FullCompression the on pdf stamper after we add any image the resulting file becomes corrupted and the images did not appears on it.

In other hand if we dont use FullCompression the file is correct with the stamped images.

There is any way to use fullCompresion on pdfStamper on pdf with added images?

Thanks for reading


Solution

  • Move this line up:

    PdfStamper.setFullCompression();
    

    Make sure that this method is used right after creating the PdfStamper instance and the problem will be solved.