本文介绍: Python代码: 把几个PDF文件拼接一个 Merge PDF files。 虽然有很多现存的APP可以轻松拼接PDF文件, 不过免费的担心广告,就用python简单写了一个程序可以很容易做到

虽然有很多现存的APP可以轻松拼接PDF文件, 不过免费的担心广告,就用python简单写了一个程序可以很容易做到

1.开辟一个专门做拼接文件夹, 我的叫”test“:

        NewDir=r“C:UsersYXDocumentsLennovotest

2. 把需要拼接pdf文件都转到该文件夹中

下面是程序代码

下载PyPDF2:

pip install PyPDF2

然后代码如下

import os
from PyPDF2 import PdfFileReader, PdfFileWriter,PdfFileMerger

NewDir=r"C:UsersYXDocumentsLennovotest"  #working director

NewName="test.pdf"
os.chdir(NewDir)  #file operation will be done in the NewDir
print(os.getcwd())


fnames=[]  #to read files
for i in os.scandir(NewDir):
    if (i.is_file() and i.name.endswith(".pdf")):
        fnames.append(i.name)

def MergePdf():
    MergedPdf=PdfFileWriter()
    TotalPages = 0
    for fn in fnames:
        input = PdfFileReader(open(fn, "rb"))
        pages= input.getNumPages()
        TotalPages += pages
        print(fn,"page numbers:%d" % pages)
        for i in range(pages):
            MergedPdf.addPage(input.getPage(i))
    print("total pages:",TotalPages)
    NewFile = open(os.path.join(NewDir, NewName), "wb")
    MergedPdf.write(NewFile)
    NewFile.close()

def MergePdf2():
    MergedPdf = PdfFileMerger()
    for fn in fnames:
        f=open(fn,"rb")
        MergedPdf.append(PdfFileReader(f))
        f.close()
    NewFile = open(os.path.join(NewDir, NewName), "wb")
    MergedPdf.write(NewFile)

MergePdf()

注意

1.pdf 文件的文件名必须与程序中的i.name.endswith(“.pdf“) 一致(要么都是大写PDF,要么都是小写pdf

2. 提供了2个子程序, 都可以用来拼接

原文地址:https://blog.csdn.net/m0_60558800/article/details/125875600

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任

如若转载,请注明出处:http://www.7code.cn/show_46354.html

如若内容造成侵权/违法违规/事实不符,请联系代码007邮箱suwngjj01@126.com进行投诉反馈,一经查实,立即删除

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注