在 pdfStamper 上使用 itext 5.5.6 和 FullCompression 将图像添加到 pdf 时出错

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

上周我们在测试期间从 itext 5.3.6 升级到 5.5.6,我们检测到在启用完全压缩的现有 pdf 上添加图像时出现问题。 请参阅下一个代码示例:

  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();
}

如果我们在添加任何图像后对 pdf 压模使用 FullCompression,则生成的文件会损坏并且图像不会出现在上面。

另一方面,如果我们不使用 FullCompression,则文件是正确的,带有标记图像。

有什么方法可以在添加图像的 pdf 上使用 pdfStamper 上的 fullCompresion?

感谢阅读

将这一行上移:

PdfStamper.setFullCompression();

确保在创建PdfStamper实例后立即使用此方法,问题将得到解决。