在 Java 中添加 PDF 背景
Contents
[
Hide
]
背景工件允许您在不更改逻辑文档文本的情况下,将非内容的视觉元素放置在主页面内容后面。
向 PDF 添加背景图像
当页面应将图像显示为背景工件时,请使用此示例。
- 使用 Document 打开源 PDF,并打开图像流。
- 创建一个 BackgroundArtifact 并分配图像流。
- 将工件添加到目标页面并保存输出 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());
}
}
添加具有不透明度的背景图像
此示例将在页面内容后放置一个半透明的背景图像。
- 使用 Document 打开源 PDF,并打开图像流。
- 创建一个 BackgroundArtifact, 分配图像,并设置不透明度。
- 将工件添加到页面并保存文档。
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());
}
}
为 PDF 添加背景颜色
当页面应使用纯色背景而非图像时,请使用此示例。
- 使用 Document 打开源 PDF.
- 创建一个 BackgroundArtifact 并分配背景颜色。
- 将构件添加到页面并保存输出文件。
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());
}
}