• 欢迎访问搞代码网站,推荐使用最新版火狐浏览器和Chrome浏览器访问本网站!
  • 如果您觉得本站非常有看点,那么赶紧使用Ctrl+D 收藏搞代码吧

Python中用PyPDF2拆分pdf提取页面

python 搞java代码 3年前 (2022-05-21) 19次浏览 已收录 0个评论

有时候我们只需要pdf中的几页,或许还想把这几页内容整合成新的pdf,那该怎么做呢?

准备工作:


安装扩展库PyPDF2,参考命令

<p style="line-height: 1.75em"><span>pip install PyPDF2<br></span></p>

www#gaodaima.com来源gaodai$ma#com搞$$代**码网搞代码

代码如下:

<p style="line-height: 1.75em"><span>from PyPDF2 import PdfFileReader, PdfFileWriter
 
 
def split_pdf(filename, result, start=0, end=None):
    """从filename中提取[start,end)之间的页码内容保存为result"""
    # 打开原始 pdf 文件
    pdf_src = PdfFileReader(filename)
    if end is None:
        # 获取页数
        end = pdf_src.getNumPages()
    with open(result, "wb") as fp:
        # 创建空白pdf文件
        pdf = PdfFileWriter()
        # 提取页面内容,写入空白文件
        for num in range(start, end):
            pdf.addPage(pdf_src.getPage(num))
        # 写入结果pdf
        pdf.write(fp)
 
 
fn = r"G:a001第九天.pdf"
split_pdf(fn, "1.pdf", 0, 3)
split_pdf(fn, "2.pdf", 1, 3)
split_pdf(fn, "3.pdf", 2, 3)<br></span></p>

遇见的问题一:


<p style="line-height: 1.75em"><span>Traceback (most recent call last):
  File "G:/a001/pdf.py", line 22, insplit_pdf(fn, "1.pdf", 0, 3)
  File "G:/a001/pdf.py", line 7, in split_pdf
    pdf_src = PdfFileReader(filename)
  File "E:project_luffyluffylibsite-packagesPyPDF2pdf.py", line 1084, in __init__
    self.read(stream)
  File "E:project_luffyluffylibsite-packagesPyPDF2pdf.py", line 1901, in read
    raise utils.PdfReadError("Could not find xref table at specified location")
PyPDF2.utils.PdfReadError: Could not find xref table at specified location<br></span></p>

还没有找到好的解决问题的办法,但是我在操作过程中换了一个新的pdf文件就成功了,猜测是你的pdf文件出了问题。

遇见的问题二:


在解决了上面的问题之后,程序可以正常的使用,但是还会出一个问题:

<p style="line-height: 1.75em"><span>PdfReadWarning: Xref table not zero-indexed. ID numbers for objects will be corrected. [pdf.py:1736]<br></span></p>

虽然不影响,但是体验不好啊 ,继续解决吧

<p style="line-height: 1.75em"><span>import sys
 
if not sys.warnoptions:
    import warnings
    warnings.simplefilter("ignore")<br></span></p>

上面代码要加在最上面

关于PyPDF2的内容,昨天有详细讲解过,不会的小伙伴可以查看:进阶PDF,就用Python(PyPDF2模块)

来源:搞代码网:原文地址:https://www.gaodaima.com


搞代码网(gaodaima.com)提供的所有资源部分来自互联网,如果有侵犯您的版权或其他权益,请说明详细缘由并提供版权或权益证明然后发送到邮箱[email protected],我们会在看到邮件的第一时间内为您处理,或直接联系QQ:872152909。本网站采用BY-NC-SA协议进行授权
转载请注明原文链接:Python中用PyPDF2拆分pdf提取页面
喜欢 (0)
[搞代码]
分享 (0)
发表我的评论
取消评论

表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址