Java PDF生成水印 代码
时间: 2023-03-15 18:20:51 浏览: 109
使用 Java 可以使用 Apache PDFBox 库来生成 PDF 文档的水印。以下是一个示例代码:
```
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDFont;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
public class AddWatermark {
public static void main(String[] args) throws IOException {
// Load the PDF document
File file = new File("input.pdf");
PDDocument document = PDDocument.load(file);
// Create a font object
PDFont font = PDType1Font.HELVETICA_BOLD;
// Iterate over each page of the document
for (PDPage page : document.getPages()) {
// Start a new content stream which will "hold" the to be created content
PDPageContentStream contentStream = new PDPageContentStream(document, page, PDPageContentStream.AppendMode.APPEND, true);
// Set the font and font size
contentStream.setFont(font, 36);
// Set the color of the text
contentStream.setNonStrokingColor(255, 255, 255);
// Define the text to be added as watermark
String text = "CONFIDENTIAL";
// Get the width of the text
float textWidth = font.getStringWidth(text) / 1000 * 36;
// Get the height of the text
float textHeight = font.getFontDescriptor().getFontBoundingBox().getHeight() / 1000 * 36;
// Calculate the position of the text
float x = (page.getMediaBox().getWidth() - textWidth) / 2;
float y = (page.getMediaBox().getHeight() - textHeight) / 2;
// Rotate the text 45 degrees counterclockwise
contentStream.saveGraphicsState();
contentStream.transform(Matrix.getRotateInstance(-45, x, y));
// Draw the text on the page
contentStream.beginText();
contentStream.newLineAtOffset(x, y);
contentStream.showText(text);
contentStream.endText();
// Restore the graphics state
contentStream.restoreGraphicsState();
// Close the content stream
contentStream.close();
}
// Save the PDF document
document.save("output.pdf");
// Close the document
document.close();
}
}
```
这段代码会读取名为 `input.pdf` 的文档,在每一页上生成一个文本水印 “CONFIDENTIAL”,并将生成的文档保存为 `output
阅读全文