iText:如何在同一文档中插入背景图像以刷新响应

Joh*_*ohn 5 java itext

我正在创建一个PDF并编写流作为响应.在写入流之前,我想在所有页面中添加背景图像作为水印,以便通过响应刷新的PDF文档是带有水印的最终文档.

嗨,这是我的代码示例.任何帮助都会很有帮助

private static String generatePDF(HttpServletRequest request, HttpServletResponse   response, String fileName) throws Exception
{
    Document document = null;
    PdfWriter writer = null;
    FileOutputStream fos = null;
    try
    {
       fos = new FileOutputStream(fileName);
       Document document = new Document(PageSize.A4);
       writer = PdfWriter.getInstance(document, fos);
       document.open();

       /**
        * Adding tables and cells and other stuff required
        **/

       return pdfFileName;
  } catch (Exception e) {
       FileUtil.deleteFile(fileName);
       throw e
  } finally {
    if (document != null) {
        document.close();
    }
    fos.flush();
  }
}
Run Code Online (Sandbox Code Playgroud)

我现在想使用下面的代码添加背景图像,并将输出PDF写入相同的流

PdfReader sourcePDFReader = null;
try
{
   sourcePDFReader = new PdfReader(sourcePdfFileName);
   int noOfPages = sourcePDFReader.getNumberOfPages();
   PdfStamper stamp = new PdfStamper(sourcePDFReader, new FileOutputStream(destPdfFileName));
   int i = 0;
   Image templateImage = Image.getInstance(templateImageFile);
   templateImage.setAbsolutePosition(0, 0);
   PdfContentByte tempalteBytes;
   while (i < noOfPages) {
       i++;
       tempalteBytes = stamp.getUnderContent(i);
       tempalteBytes.addImage(templateImage);
   }
   stamp.close();
   return destPdfFileName;
} catch (Exception ex) {
   LOGGER.log(Level.INFO, "Error when applying tempalte image as watermark");
} finally {
     if (sourcePDFReader != null) {
         sourcePDFReader.close();
     }
}
Run Code Online (Sandbox Code Playgroud)

Sea*_*lly 12

我使用布鲁诺的第一个(推荐)方法解决了这个问题.

1)使用事件创建页面事件助手onEndPage:

class PDFBackground extends PdfPageEventHelper {

    @Override
    void onEndPage(PdfWriter writer, Document document) {
        Image background = Image.getInstance("myimage.png");
        // This scales the image to the page,
        // use the image's width & height if you don't want to scale.
        float width = document.getPageSize().getWidth();
        float height = document.getPageSize().getHeight();
        writer.getDirectContentUnder()
                .addImage(background, width, 0, 0, height, 0, 0);
    }

}
Run Code Online (Sandbox Code Playgroud)

2)创建编写器时,注册页面事件助手:

PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
writer.setPageEvent(new PDFBackground());
Run Code Online (Sandbox Code Playgroud)


Bru*_*gie 2

您可以选择以下两个选项:

  1. 在页面事件中使用背景图像(到onEndPage() 方法中的“under”内容)/
  2. 在内存中创建第一个 PDF,然后使用您发布的代码在第二遍中添加背景图像。

我更喜欢选项 1。