我没有得到任何关于在PDF文件中添加文本水印的教程?请大家给我指点一下,我对PDFBOX很陌生。
它不是重复的,评论中的链接对我没有帮助。我想添加文本,而不是图像到pdf。
发布于 2016-09-27 05:32:18
下面是一个使用PDFBox 2.0.2的示例。这将加载一个PDF,并在右下角以红色透明字体写入一些文本。如果是多页PDF,水印将出现在每一页上。它可能还没有为生产做好准备,因为我不确定是否有一些额外的null条件需要检查,但它应该会让您在正确的方向上运行。
请记住,这段特定的代码不会修改原始的PDF,但会使用Tmp_(文件名)作为输出创建一个新的PDF。
private static void watermarkPDF (File fileStored) {
File tmpPDF;
PDDocument doc;
tmpPDF = new File(fileStored.getParent() + System.getProperty("file.separator") +"Tmp_"+fileStored.getName());
doc = PDDocument.load(fileStored);
for(PDPage page:doc.getPages()){
PDPageContentStream cs = new PDPageContentStream(doc, page, AppendMode.APPEND, true, true);
String ts = "Some sample text";
PDFont font = PDType1Font.HELVETICA_BOLD;
float fontSize = 14.0f;
PDResources resources = page.getResources();
PDExtendedGraphicsState r0 = new PDExtendedGraphicsState();
r0.setNonStrokingAlphaConstant(0.5f);
cs.setGraphicsStateParameters(r0);
cs.setNonStrokingColor(255,0,0);//Red
cs.beginText();
cs.setFont(font, fontSize);
cs.setTextMatrix(Matrix.getTranslateInstance(0f,0f));
cs.showText(ts);
cs.endText();
}
cs.close();
}
doc.save(tmpPDF);
}https://stackoverflow.com/questions/39609617
复制相似问题