Agregar fondos PDF en Java

Los artefactos de fondo le permiten colocar elementos visuales que no son contenido detrás del contenido principal de la página sin cambiar el texto lógico del documento.

Agregar una imagen de fondo a un PDF

Utilice este ejemplo cuando la página debe mostrar una imagen como un artefacto de fondo.

  1. Abra el PDF de origen con Document y abra el flujo de imagen.
  2. Cree un BackgroundArtifact y asigne el flujo de imagen.
  3. Agregue el artefacto a la página de destino y guarde el PDF de salida.
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());
    }
}

Agregar una imagen de fondo con opacidad

Este ejemplo coloca una imagen de fondo semitransparente detrás del contenido de la página.

  1. Abra el PDF de origen con Document y abra el flujo de imagen.
  2. Cree un BackgroundArtifact, asigne la imagen, y establezca la opacidad.
  3. Agregue el artefacto a la página y guarde el documento.
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());
    }
}

Agregar un color de fondo a un PDF

Utilice este ejemplo cuando la página deba usar un color de fondo sólido en lugar de una imagen.

  1. Abra el PDF de origen con Document.
  2. Cree un BackgroundArtifact y asigne el color de fondo.
  3. Agregue el artefacto a la página y guarde el archivo de salida.
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());
    }
}

Temas relacionados