2
votes

I have an application that creates a PDF file using Java, Spring and IText.

I want to add a watermark to the pdf.

I have found plenty of examples of adding a watermark to an already saved PDF. I want to add the watermark before the PDF is saved.

I found an example of doing what I want using ITextSharp, however, it is for .NET. I am using the following code in my class that creates the pdf document.

protected void buildPdfDocument(Map model, Document document, PdfWriter writer, HttpServletRequest request,
            HttpServletResponse response) throws Exception {

    response.setContentType("application/pdf");
    ProgramCmd programCmd = (ProgramCmd) request.getSession().getAttribute("programCmd ");
    List<Courses> list = programCmd.getCoursesList();
    List<Events> eventsList = programCmd.getEventsList();
    FONT_SIZE_16_BOLD.setColor(232, 177, 0);
    // Print Header
    Paragraph paragraph = new Paragraph("Title",FONT_SIZE_16_BOLD);
    paragraph.setAlignment(Element.ALIGN_CENTER);
    document.add(paragraph);
    paragraph = new Paragraph("***This is Not Official***",FONT_SIZE_12_BOLD);
    paragraph.setAlignment(Element.ALIGN_CENTER);
    document.add(paragraph);
    paragraph = new Paragraph("Create Date: " + todaysDate,FONT_SIZE_12_BOLD);
    paragraph.setAlignment(Element.ALIGN_CENTER);
    document.add(paragraph);
}

Please let me know if you want me to post other code.

Thank you.

2

2 Answers

1
votes

The first edition of the book "iText in Action" has an example "WatermarkExample.java" in chapter 14. You can download the source of the example at Manning's website, though of course, I also encourage you to purchase the book!

0
votes

Thank you for promoting my book, GreyBeardedGeek (deserves an upvote).

Let me elaborate on the matter:

It's not clear if you want to add the watermark while you're creating the document (that's done with page events), or after the document is created (that's done with PdfStamper).

These are examples of both options:

  1. In http://itextpdf.com/examples/iia.php?id=105 we extend PdfPageEventHelper and implement the onEndPage() method. As documented, you shouldn't add anything to the Document class, nor use the onStartPage() method to add content. (More info in iText in Action - Second Edition).
  2. In http://itextpdf.com/examples/iia.php?id=119 we add a background to an existing PDF using PdfStamper and PdfReader. You don't need to have a file on disk to create a PdfReader instance. You can create the file in memory first (e.g. using a ByteArrayOutputStream) and pass the bytes to the PdfReader constructor.