13

我正在尝试使用 Python 将几个 PDF 文件组合成一个 PDF 文件。我已经尝试过 PyPDF 和 PyPDF2 - 在某些文件上,它们都抛出了同样的错误:

PdfReadError:未找到 EOF 标记

这是我的代码 (page_files) 是要组合的 PDF 文件路径列表:

# use pypdf to combine pdf pages
output = PdfFileWriter()
for pf in page_files:
    filestream = file(pf, "rb")
    pdf = PdfFileReader(filestream)            
    for num in range(pdf.getNumPages()):
        output.addPage(pdf.getPage(num))            

# write final file
outputStream = file(pdf_full_path, "wb")
output.write(outputStream)
outputStream.close()

我已经阅读了一些关于该主题的 StackOverflow 线程,但没有一个包含有效的解决方案。如果您已使用 Python 成功合并 PDF 文件,我很想听听如何。谢谢!

4

1 回答 1

0

是否还有人在寻找合并 pdf 的“列表”:

注意:使用 glob 获取正确的文件列表。<- 这真的会让你的一天很安全^^

看看这个:glob 模块参考

from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter
import os
import glob

class MergeAllPDF:
    def __init__(self):
        self.mergelist = []

    def create(self, filepath, outpath, outfilename):
        self.outfilname = outfilename
        self.filepath = filepath
        self.outpath = outpath
        self.pdfs = glob.glob(self.filepath)
        self.myrange = len(self.pdfs)

        for _ in range(self.myrange):
            if self.pdfs:
                self.mergelist.append(self.pdfs.pop(0))
        self.merge()

    def merge(self):
        if self.mergelist:
            self.merger = PdfFileMerger()
            for pdf in self.mergelist:
                self.merger.append(open(pdf, 'rb'))  
            self.merger.write(self.outpath + "%s.pdf" % (self.outfilname))
            self.merger.close()
            self.mergelist = []
        else:
            print("mergelist is empty please check your input path")

# example how to use
#update your path here:


inpath = r"C:\Users\Fabian\Desktop\mergeallpdfs\scan\*.pdf" #here are your single page pdfs stored
outpath = r"C:\Users\Fabian\Desktop\mergeallpdfs\output\\" #here your merged pdf will be stored

b = MergeAllPDF()
b.create(inpath, outpath, "mergedpdf")
于 2018-10-22T12:37:11.567 回答