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

前端 未结 3 1540
野趣味
野趣味 2021-01-12 21:19

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 flu

3条回答
  •  轮回少年
    2021-01-12 21:35

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

提交回复
热议问题