使用Java编辑PDF文本

有没有办法从Java编辑PDF?
我有一个PDF文档,其中包含我需要使用Java替换的文本的占位符,但我看到的所有库都是从头开始创建PDF和小编辑function。
无论如何我可以编辑PDF或这是不可能的吗?

你可以用iText做到这一点。 我用以下代码测试了它。 它在现有PDF的每个页面上添加了一大块文本和一个红色圆圈。

/* requires itextpdf-5.1.2.jar or similar */ import java.io.*; import com.itextpdf.text.DocumentException; import com.itextpdf.text.pdf.*; public class AddContentToPDF { public static void main(String[] args) throws IOException, DocumentException { /* example inspired from "iText in action" (2006), chapter 2 */ PdfReader reader = new PdfReader("C:/temp/Bubi.pdf"); // input PDF PdfStamper stamper = new PdfStamper(reader, new FileOutputStream("C:/temp/Bubi_modified.pdf")); // output PDF BaseFont bf = BaseFont.createFont( BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED); // set font //loop on pages (1-based) for (int i=1; i<=reader.getNumberOfPages(); i++){ // get object for writing over the existing content; // you can also use getUnderContent for writing in the bottom layer PdfContentByte over = stamper.getOverContent(i); // write text over.beginText(); over.setFontAndSize(bf, 10); // set font and size over.setTextMatrix(107, 740); // set x,y position (0,0 is at the bottom left) over.showText("I can write at page " + i); // set text over.endText(); // draw a red circle over.setRGBColorStroke(0xFF, 0x00, 0x00); over.setLineWidth(5f); over.ellipse(250, 450, 350, 550); over.stroke(); } stamper.close(); } } 

看看iText和这个示例代码

看看aspose和这个示例代码

您可以使用Itext进行有限的编辑,但PDF是一种结束文件格式,因此您无法执行任何过于复杂的操作。 我写了一篇文章解释了一些限制: PDF格式和样式信息 。