Python PyPDF2 同一文件中的多个注释

Python PyPDF2 Multiple Annotations in The Same File

提问人:Vinícius Amaral 提问时间:11/3/2023 最后编辑:Vinícius Amaral 更新时间:11/3/2023 访问量:27

问:

我正在尝试在同一 PDF 中添加多个注释。 我只想打开一个 PDF 并一次关闭一次,当它打开时,我想写多个注释。下面你可以看到我的代码。

def BatchAnnotate(myPDFPath, myPDFOutput, myAllNotes):

    pdf_path = myPDFPath
    reader = PdfReader(pdf_path)
    
    writer = PdfWriter()
    
    for myNote in myAllNotes:

        myPageIndex = myNote[0]
        myText = myNote[1]
        myPosition = myNote[2]
        # Fill the writer with the pages you want
        myX = ConvertMM2Pixel(myPosition[0])
        myY = ConvertMM2Pixel(myPosition[1])
        
        box = reader.pages[0].mediabox

        myTotalPages = len(reader.pages)
        
        page = reader.pages[myPageIndex]
        writer.add_page(page)

        
        annotation = AnnotationBuilder.text(
            text=myText,
            rect= (myX, int(box[3] - myY), myX, int(box[3] - myY)), #(50, 550, 200, 650),
            flags=15,
            open=False,
            )
        writer.add_annotation(page_number=myPageIndex, annotation=annotation)


    # Write the annotated file to disk
    with open(myPDFOutput, "wb") as fp:
        writer.write(fp)

我最大的问题是我的脚本每次交互都会创建一个页面,但是当我删除行 writer.add_page(page) 时,我的脚本不起作用。

您可以在下面看到错误。

ile "/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/PyPDF2/_writer.py", line 2199, in add_annotation
to_add[NameObject("/P")] = self.get_object(self._pages)["/Kids"][page_number]  # type: ignore
                           ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~^^^^^^^^^^^^^

IndexError:列出超出范围的索引

有人可以帮助我吗?请。

python pypdf

评论

0赞 cards 11/3/2023
“当我删除行 writer.add_page(page) 时,我的脚本不起作用”是什么意思?错误消息(以防发布完整的回溯错误)?不是想要的结果?
0赞 cards 11/3/2023
您的代码或多或少是好的,有关类似示例,另请参阅文档。 需要构建带有注释的 PDFwriter.add_page
0赞 Vinícius Amaral 11/3/2023
这段代码,我从文档中提取并根据我的需要进行调整。我writer.add_page是需要的,为什么它在我的文档中创建了很多页面。我的错误在哪里?
0赞 Random Rush Girl 11/3/2023
你能发布整个错误消息吗?

答: 暂无答案