Python-71 用pypdf2实现两个pdf文件的mergeh合并 2020-09-25

用pypdf2实现两个或者多个pdf文件的merge,即合并。具体代码与实现如下:
备注: pypdf2 可以实现pdf阅读,合并,横向纵向转换,合并,提取文本,改为word等。

# pdf_merging.py

from PyPDF2 import PdfFileReader, PdfFileWriter

def merge_pdfs(paths, output):
    pdf_writer = PdfFileWriter()

    for path in paths:
        pdf_reader = PdfFileReader(path)
        for page in range(pdf_reader.getNumPages()):
            # Add each page to the writer object
            pdf_writer.addPage(pdf_reader.getPage(page))

    # Write out the merged PDF
    with open(output, 'wb') as out:
        pdf_writer.write(out)

if __name__ == '__main__':
    # SET UP THE PATH 
    paths = ['C:/Users/Mr.R/Desktop/test1/A.pdf', 'C:/Users/Mr.R/Desktop/test1/B.pdf']
    merge_pdfs(paths, output='C:/Users/Mr.R/Desktop/test1/merged.pdf')

原始文件分别为:


image.png
image.png

合并结果为:


image.png

你可能感兴趣的:(Python-71 用pypdf2实现两个pdf文件的mergeh合并 2020-09-25)