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

How can I insert a word in a sentence of a PDF content in Java?

我想在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 不是所见即所得的格式。在内部,它更像是一个包含代码的文件。它具有围绕光标移动以及在光标尖端绘制文本和图形的说明。

事实上,大多数指令都被打包到 "objects" 中。所有对象都放在一个字典中,该字典使用字节偏移量来引用它们。

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

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

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