PDFLayers添加图片水印java代码
时间: 2023-12-02 11:05:29 浏览: 60
给图片添加文字水印的Java代码
下面是一个使用PDFLayers库添加图片水印的Java代码示例:
```java
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.graphics.image.PDImageXObject;
import org.apache.pdfbox.pdmodel.graphics.optionalcontent.PDOptionalContentGroup;
import org.apache.pdfbox.pdmodel.graphics.optionalcontent.PDOptionalContentProperties;
import org.apache.pdfbox.pdmodel.graphics.optionalcontent.PDOptionalContentState;
import org.apache.pdfbox.pdmodel.graphics.optionalcontent.PDOptionalContentSubGroup;
import org.apache.pdfbox.pdmodel.graphics.optionalcontent.PDVisibilityPolicy;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class PDFWatermarkExample {
public static void main(String[] args) throws IOException {
// Load PDF document
PDDocument document = PDDocument.load(new File("input.pdf"));
// Load watermark image
BufferedImage watermarkImage = ImageIO.read(new File("watermark.png"));
// Create optional content group for watermark
PDOptionalContentGroup watermarkGroup = new PDOptionalContentGroup("Watermark");
watermarkGroup.setPrinted(false);
PDOptionalContentProperties watermarkProperties = new PDOptionalContentProperties();
watermarkProperties.setGroup(watermarkGroup);
PDOptionalContentState watermarkState = new PDOptionalContentState();
watermarkState.setOn(true);
watermarkProperties.setCurrentState(watermarkState);
// Add watermark image to each page
for (PDPage page : document.getPages()) {
// Create layer for watermark on this page
PDOptionalContentGroup pageGroup = new PDOptionalContentGroup("Page " + (document.getPages().indexOf(page) + 1));
pageGroup.setPrinted(false);
PDOptionalContentProperties pageProperties = new PDOptionalContentProperties();
pageProperties.setGroup(pageGroup);
PDOptionalContentState pageState = new PDOptionalContentState();
pageState.setOn(true);
pageProperties.setCurrentState(pageState);
// Add layer to page content
PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true);
contentStream.beginOptionalContent(pageGroup);
// Add watermark image to layer
PDImageXObject watermarkXObject = PDImageXObject.createFromFileByContent(watermarkImage, document);
contentStream.drawImage(watermarkXObject, 0, 0, page.getMediaBox().getWidth(), page.getMediaBox().getHeight());
contentStream.endOptionalContent();
contentStream.close();
}
// Save document
document.save(new File("output.pdf"));
document.close();
}
}
```
此代码将加载名为“input.pdf”的PDF文档,并将名为“watermark.png”的图像作为水印添加到每个页面上。它使用PDFLayers库来创建可选内容组和层,并将水印图像添加到正确的层中。最后,它将保存修改后的文档,命名为“output.pdf”。
阅读全文