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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12677207/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:48:17  来源:igfitidea点击:

iText : How do I insert background image in the same document to be flushed to response

javaitext

提问by John

I am creating a PDF and writing the stream in response. Before writing in the stream, I want to add a background image as watermark in all the pages so that PDF document flushed through response is the final one with watermark.

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

Hi this is my code sample. Any help would be much appriciated

嗨,这是我的代码示例。任何帮助都会非常有用

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

I now would like to add a background image using the below code and write the output PDF to the same stream

我现在想使用以下代码添加背景图像并将输出 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();
     }
}

回答by Sean Connolly

I solved this using Bruno's first (recommended) approach.

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

1) Create a page event helper with an onEndPageevent:

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

}

2) When creating your writer, register your page event helper:

2)在创建你的作家时,注册你的页面事件助手:

PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
writer.setPageEvent(new PDFBackground());

回答by John

I have solved this with Bruno's second option. Here is the code.

我已经用布鲁诺的第二个选项解决了这个问题。这是代码。

public static String addBackgroundImageToPDF(ByteArrayOutputStream bos, String destPdfFileName, String templateImageFile)
{
  PdfReader sourcePDFReader = null;
  try
  {
        sourcePDFReader = new PdfReader(bos.toByteArray());
        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 template image as watermark");
  }
  finally
  {
        if (sourcePDFReader != null)
        {
              sourcePDFReader.close();
        }
  }
}

回答by Bruno Lowagie

You can choose between two options:

您可以在两个选项之间进行选择:

  1. Use the background image in a page event (to the 'under' content in the onEndPage() method)/
  2. Create the first PDF in memory, then add the background image in a second pass using the code you posted.
  1. 在页面事件中使用背景图像(到onEndPage() 方法中的“下”内容)/
  2. 在内存中创建第一个 PDF,然后使用您发布的代码在第二遍中添加背景图像。

I prefer option 1.

我更喜欢选项1。