Add PDF Backgrounds in Java

Background artifacts let you place non-content visual elements behind the main page content without changing the logical document text.

Add a background image to a PDF

Use this example when the page should display an image as a background artifact.

  1. Open the source PDF Document and the image input stream.
  2. Create a BackgroundArtifact and assign the image stream.
  3. Add the artifact to the target page and save the output PDF.
public static void addBackgroundImageToPdf(Path inputFile, Path imageFile, Path outputFile) throws Exception {
    try (Document document = new Document(inputFile.toString());
         InputStream imageStream = Files.newInputStream(imageFile)) {
        BackgroundArtifact artifact = new BackgroundArtifact();
        artifact.setBackgroundImage(imageStream);
        document.getPages().get_Item(1).getArtifacts().add(artifact);
        document.save(outputFile.toString());
    }
}

Add a background image with opacity

This example places a semi-transparent background image behind the page content.

  1. Open the source PDF Document and image stream.
  2. Create a BackgroundArtifact, assign the image, and set the opacity.
  3. Add the artifact to the page and save the document.
public static void addBackgroundImageWithOpacityToPdf(Path inputFile, Path imageFile, Path outputFile)
        throws Exception {
    try (Document document = new Document(inputFile.toString());
         InputStream imageStream = Files.newInputStream(imageFile)) {
        BackgroundArtifact artifact = new BackgroundArtifact();
        artifact.setBackgroundImage(imageStream);
        artifact.setOpacity(0.5);
        document.getPages().get_Item(1).getArtifacts().add(artifact);
        document.save(outputFile.toString());
    }
}

Add a background color to a PDF

Use this example when the page should use a solid background color instead of an image.

  1. Open the source PDF Document.
  2. Create a BackgroundArtifact and assign the background color.
  3. Add the artifact to the page and save the output file.
public static void addBackgroundColorToPdf(Path inputFile, Path outputFile) {
    try (Document document = new Document(inputFile.toString())) {
        BackgroundArtifact artifact = new BackgroundArtifact();
        artifact.setBackgroundColor(Color.getDarkKhaki().toRgb());
        document.getPages().get_Item(1).getArtifacts().add(artifact);
        document.save(outputFile.toString());
    }
}