Skip to main content
 首页 » 编程设计

python之如何在 Python 3 中删除 pdf 中的注释

2024年11月24日17sky-heaven

我最初的目标是去除 PDF 页面上的大量白边。

然后我发现这个目的可以通过使用下面的代码缩放页面来实现,但是注释没有缩放。

import PyPDF2 
 
# This works fine 
with open('old.pdf', 'rb') as pdf_obj: 
    pdf = PyPDF2.PdfFileReader(pdf_obj) 
    out = PyPDF2.PdfFileWriter() 
    for page in pdf.pages: 
        page.scale(2, 2) 
        out.addPage(page) 
    with open('new.pdf', 'wb') as f:  
        out.write(f) 
 
# This attempts to remove annotations 
with open('old.pdf', 'rb') as pdf_obj: 
    pdf = PyPDF2.PdfFileReader(pdf_obj) 
    page = pdf.pages[2] 
    print(page['/Annots'], '\n\n\n\n') 
    page.Annots = [] 
    print(page['/Annots']) 

有没有办法去掉注解?或者任何可以帮助我摆脱白边的建议。

请您参考如下方法:

PdfFileWriter.removeLinks() 方法删除链接和注释。因此,如果您不介意丢失两者,则可以在您的第一个代码块中添加 out.removeLinks(),该代码块运行良好。