如何在 Java 中的 PDF 内容的句子中插入单词?



我想在PDF内容的句子中添加一个单词。

例如:

This is a sample content.

我想在该内容中插入一个单词,例如此输出。

This is a nice sample content.

这是我在互联网上找到的itextPdf的示例代码。假设内容已经存在,我们希望通过在句子中添加文本来修改它。

try {
//Create PdfReader instance.
PdfReader pdfReader =
new PdfReader(SRC);
//Create PdfStamper instance.
PdfStamper pdfStamper = new PdfStamper(pdfReader,
new FileOutputStream(DEST));
//Create BaseFont instance.
BaseFont baseFont = BaseFont.createFont(
BaseFont.TIMES_ROMAN,
BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
//Get the number of pages in pdf.
int pages = pdfReader.getNumberOfPages();
System.out.println(pdfStamper.getOverContent(1));
//Iterate the pdf through pages.
for(int i=1; i<=pages; i++) {
//Contain the pdf data.
PdfContentByte pageContentByte =
pdfStamper.getOverContent(i);
pageContentByte.setFlatness(89);
pageContentByte.beginText();
//Set text font and size.
pageContentByte.setFontAndSize(baseFont, 14);
pageContentByte.setTextMatrix(50, 720);
//Write text
pageContentByte.setWordSpacing(12);
pageContentByte.showText("hello world");
pageContentByte.endText();
}
//Close the pdfStamper.
pdfStamper.close();
System.out.println("PDF modified successfully.");
} catch (Exception e) {
e.printStackTrace();
}

我尝试了itextPdf和PdfBox,但它们都不起作用。

我可以使用 pdfbox 的 PDFStreamParser 获取 pdf 文档中的对象。

PDFOperator{Td}, COSArray{[COSString{Name }, COSFloat{163.994}, COSString{____________________________________________________}, COSFloat{-8.03223}, COSString{________________________________________________________}]}, PDFOperator{TJ}, COSInt{19}, PDFOperator{TL}, PDFOperator{T*}, COSArray{[COSString{T}, COSInt{36}, COSString{itle}, COSFloat{0.997925}, COSString{ }, COSFloat{-94.9982}, COSString{_____________________________________________________________________________________________________________}]}, PDFOperator{TJ}, PDFOperator{T*}, COSArray{[

如何实现插入文本的代码?

不是。

Pdf 不是所见即所得的格式。在内部,它更像是一个包含代码的文件。它具有在光标周围移动以及在光标尖端绘制文本和图形的说明。

还有一个事实是,大多数指令都被打包成"对象"。所有对象都放置在使用字节偏移量引用它们的字典中。

因此,在 pdf 文档中插入任何内容都会导致 2 个级别的问题。

  1. 你会弄乱文档中所有内容的字节偏移
  2. 您需要解密所有现有的呈现操作以理解文档(派生文本行、段落等结构(,以便在插入内容后可以正确地重新排列内容。

因此,我的简短回答。你不能。这立即解释了为什么您尝试过的pdf工具包都无法做到这一点。这简直是一项极其艰巨的任务。

最新更新