使用 PyPDF2 合并 PDF 文件

Python yxl ⋅ 于 2020-04-14 20:33:55 ⋅ 831 阅读

pdf_combine(pdfs=[], newFile="")

将多个pdf合并成一个。
此函数需要安装PyPDF2包
the function need to install PyPDF2

pip install PyPDF2

参数:

pdfs: a list of strings, an empty string (default), optional,

要合并的pdf路径的list,选项:

  • list of strings (not empty): 在新的pdf中按照list顺序写入list中pdf的内容
  • empty string: print出错误指示,无法形成新的pdf

newFile: string or None (default), optional,

即将形成的新pdf路径,选项:

  • string: 在这个新的路径下形成pdf
  • None: 新的pdf将使用pdfs这个list中第一个路径的位置,并在文件名后增加"_new"

Combine multiple pdfs into single file.

Parameters:

pdfs: a list strings, an empty string (default), optional,
The list of paths of pdfs that is going to be combined.options:

  • list of strings (not empty): New pdf will be written with the order of list.
  • empty string: Error will be printed, stated that the combination cannot be done.

newFile: string or None (default), optional,

The path of new pdf that the function is going to write combined content in. options:

  • string: The new pdf will be formed with the path provided.
  • None: The new pdf will be formed with the same name and directory as the first pdf file in the list pdfs with "_new" after its filename.

Code

import PyPDF2

def pdf_comb(pdfs=[],newFile=None):

    if len(pdfs)==0:
        print("cannot combing pdfs without pdf given")
    else:
        newName=pdfs[0].replace(".pdf","_new.pdf")

    if newFile!=None:
        newName=newFile

    pdfWriter = PyPDF2.PdfFileWriter()
    pdf_files=[]

    with open(newName, 'wb') as comb_pdf:
        for i in range(len(pdfs)):
            pdf_files.append(open(pdfs[i],'rb'))
            pdfReader=PyPDF2.PdfFileReader(pdf_files[i])
            for page in range(pdfReader.numPages):
                pageObj = pdfReader.getPage(page)
                pdfWriter.addPage(pageObj)

        pdfWriter.write(comb_pdf)

    comb_pdf.close()
    for i in range(len(pdfs)):
        pdf_files[i].close()

    print("Done! files number:",len(pdfs))

Examples

pdf_s=["C:\\Users\\yexue\\Documents\\UG\\ST221 Assignment1.pdf","C:\\Users\\yexue\\Documents\\UG\\st218_weeks1and2.pdf","C:\\Users\\yexue\\Documents\\UG\\st218_ex1_2019.pdf"]
newName="C:\\Users\\yexue\\Documents\\combined_assessment3.pdf"
pdf_comb(pdf_s, newName)

Refrence

file

回复数量: 0
    暂无评论~~
    • 请注意单词拼写,以及中英文排版,参考此页
    • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`, 更多语法请见这里 Markdown 语法
    • 支持表情,使用方法请见 Emoji 自动补全来咯,可用的 Emoji 请见 :metal: :point_right: Emoji 列表 :star: :sparkles:
    • 上传图片, 支持拖拽和剪切板黏贴上传, 格式限制 - jpg, png, gif
    • 发布框支持本地存储功能,会在内容变更时保存,「提交」按钮点击时清空
    Ctrl+Enter