Here is a sample Java program showing how to add background and foreground images to pages of a PDF document while still keeping all original page content as vector, i.e, the page still contain text, images and any vector drawing commands. This sample uses Qoppa’s PDF library jPDFProcess.

This sample program opens a source PDF, loops through the pages, create a new page for each page, adds the background image, adds all vector content of the source PDF page, adds the foreground image and finally saves the new PDF. It is possible to scale / resize or shift the source page content (which can be useful if the foreground image is a header logo for instance).

public class AddBackgroundImage
{
    public static void main (String [] args)
    {
        try
        {
            // Load document
            PDFDocument pdfDoc = new PDFDocument ("C:\\myfolder\\input.pdf", null);
 
            // load background image
            BufferedImage bgImage = ImageIO.read(new File("C:\\myfolder\\background.jpg"));
 
            // load foreground image
            BufferedImage fgImage = ImageIO.read(new File("C:\\myfolder\\foreground.jpg"));
 
            // Create new PDF for output
            PDFDocument outputPDF = new PDFDocument();
 
           for (int i=0; i< pdfDoc.getPageCount(); i++)
           {
 
              PDFPage currentPage = pdfDoc.getPage(i);
 
              // Create page of the same size as source page
              PDFPage newPage = outputPDF.appendNewPage(currentPage.getPaperWidth(), currentPage.getPaperHeight());
 
              // 1- draw background image onto page
              newPage.drawImage(bgImage, 0, 0, 
                      null, null, 
                      new ImageCompression(ImageCompression.COMPRESSION_DEFLATE, 1.0f));
 
              // 2. Overlay PDF content for current page.
               // 2. Overlay PDF content for current source page.
              //    Parameters can be chanegd to pass on 
              //    an (x,y) offset to shift content
              //    a (scalex, scaley) to resize content
              newPage.appendPageContent(currentPage, 0, 0, 1, 1, null);
 
              // 3. Draw foreground image
             newPage.drawImage(fgImage, 0, 0, 
            		  null, null, 
            		  new ImageCompression(ImageCompression.COMPRESSION_DEFLATE, 1.0f));
 
              // append the new page to the new PDF
              outputPDF.appendPage(newPage);
           }
 
            // Save the output document
           outputPDF.saveDocument ("C:\\myfolder\\output.pdf");
        }
        catch (Throwable t)
        {
            t.printStackTrace();
        }
    }
}

Download Full Java Sample Code

Tagged: