2010-08-09 52 views
55

Tôi đã thực hiện tìm kiếm và dường như không có gì liên quan trực tiếp đến câu hỏi này. Có thể sử dụng Python để hợp nhất các tệp PDF riêng biệt không?Hợp nhất các tệp PDF

Giả sử như vậy, tôi cần mở rộng thêm một chút. Tôi hy vọng sẽ lặp qua các thư mục trong một thư mục và lặp lại quy trình này.

Và tôi có thể đẩy vận may của mình, nhưng có thể loại trừ một trang có chứa trong các tệp PDF (tạo báo cáo của tôi luôn tạo ra một trang trống thừa).

Trả lời

76

Sử dụng Pypdf hoặc người thừa kế của nó PyPDF2:

Một thư viện Pure-Python được xây dựng như một bộ công cụ PDF. Nó có khả năng:
* Trang tài liệu tách theo trang,
* văn bản sáp nhập từng trang,

(và nhiều hơn nữa)

Dưới đây là một chương trình mẫu làm việc với cả hai phiên bản.

#!/usr/bin/env python 
import sys 
try: 
    from PyPDF2 import PdfFileReader, PdfFileWriter 
except ImportError: 
    from pyPdf import PdfFileReader, PdfFileWriter 

def pdf_cat(input_files, output_stream): 
    input_streams = [] 
    try: 
     # First open all the files, then produce the output file, and 
     # finally close the input files. This is necessary because 
     # the data isn't read from the input files until the write 
     # operation. Thanks to 
     # https://stackoverflow.com/questions/6773631/problem-with-closing-python-pypdf-writing-getting-a-valueerror-i-o-operation/6773733#6773733 
     for input_file in input_files: 
      input_streams.append(open(input_file)) 
     writer = PdfFileWriter() 
     for reader in map(PdfFileReader, input_streams): 
      for n in range(reader.getNumPages()): 
       writer.addPage(reader.getPage(n)) 
     writer.write(output_stream) 
    finally: 
     for f in input_streams: 
      f.close() 

if __name__ == '__main__': 
    pdf_cat(sys.argv[1:], sys.stdout) 
+17

Và bây giờ, https://pypi.python.org/pypi/PyPDF2 đó là dự án kế PyPDF –

+0

@ Iago-Lito tìm dưới đây để [này] (https://stackoverflow.com/a/37945454/1540468) trả lời. –

4

Có thể sử dụng Python để hợp nhất các tệp PDF riêng biệt không?

Có.

Ví dụ sau kết hợp tất cả các file trong một thư mục vào một tập tin PDF mới duy nhất:

#!/usr/bin/env python 
# -*- coding: utf-8 -*- 

from argparse import ArgumentParser 
from glob import glob 
from pyPdf import PdfFileReader, PdfFileWriter 
import os 

def merge(path, output_filename): 
    output = PdfFileWriter() 

    for pdffile in glob(path + os.sep + '*.pdf'): 
     if pdffile == output_filename: 
      continue 
     print("Parse '%s'" % pdffile) 
     document = PdfFileReader(open(pdffile, 'rb')) 
     for i in range(document.getNumPages()): 
      output.addPage(document.getPage(i)) 

    print("Start writing '%s'" % output_filename) 
    with open(output_filename, "wb") as f: 
     output.write(f) 

if __name__ == "__main__": 
    parser = ArgumentParser() 

    # Add more options if you like 
    parser.add_argument("-o", "--output", 
         dest="output_filename", 
         default="merged.pdf", 
         help="write merged PDF to FILE", 
         metavar="FILE") 
    parser.add_argument("-p", "--path", 
         dest="path", 
         default=".", 
         help="path of source PDF files") 

    args = parser.parse_args() 
    merge(args.path, args.output_filename) 
1

đây, http://pieceofpy.com/2009/03/05/concatenating-pdf-with-python/, đưa ra một giải pháp.

tương tự:

from pyPdf import PdfFileWriter, PdfFileReader 

def append_pdf(input,output): 
    [output.addPage(input.getPage(page_num)) for page_num in range(input.numPages)] 

output = PdfFileWriter() 

append_pdf(PdfFileReader(file("C:\\sample.pdf","rb")),output) 
append_pdf(PdfFileReader(file("c:\\sample1.pdf","rb")),output) 
append_pdf(PdfFileReader(file("c:\\sample2.pdf","rb")),output) 
append_pdf(PdfFileReader(file("c:\\sample3.pdf","rb")),output) 

    output.write(file("c:\\combined.pdf","wb")) 
51

Các PyPdf2 thư viện mới có một lớp PdfMerger, có thể được sử dụng như vậy.

dụ:

from PyPDF2 import PdfFileMerger 

pdfs = ['file1.pdf', 'file2.pdf', 'file3.pdf', 'file4.pdf'] 

merger = PdfFileMerger() 

for pdf in pdfs: 
    merger.append(open(pdf, 'rb')) 

with open('result.pdf', 'wb') as fout: 
    merger.write(fout) 

Phương pháp append dường như đòi hỏi một đối tượng file lười biếng. Đó là nó không đọc tập tin ngay lập tức. Dường như đợi cho đến khi phương thức write được gọi. Nếu bạn sử dụng một phạm vi mở (ví dụ: with), nó sẽ thêm các trang trống vào tệp kết quả, vì tệp đầu vào được đóng tại điểm đó.

Cách dễ nhất để tránh điều này nếu thời gian xử lý tệp là một vấn đề, là vượt qua append chuỗi tên tệp và cho phép tệp đó xử lý thời lượng tệp.

ví dụ:

from PyPDF2 import PdfFileMerger 

pdfs = ['file1.pdf', 'file2.pdf', 'file3.pdf', 'file4.pdf'] 

merger = PdfFileMerger() 

for pdf in pdfs: 
    merger.append(pdf) 

merger.write("result.pdf") 
1

Các pdfrw library có thể làm được điều này khá dễ dàng, giả sử bạn không cần phải giữ gìn dấu trang và chú thích, và PDF của bạn không được mã hóa. cat.py là tập lệnh ghép nối ví dụ và subset.py là tập lệnh đặt trước trang mẫu.

Phần liên quan của kịch bản nối - giả inputs là một danh sách các tên tập tin đầu vào, và outfn là một tên tập tin đầu ra:

from pdfrw import PdfReader, PdfWriter 

writer = PdfWriter() 
for inpfn in inputs: 
    writer.addpages(PdfReader(inpfn).pages) 
writer.write(outfn) 

Như bạn có thể nhìn thấy từ này, nó sẽ là khá dễ dàng để bỏ trang cuối cùng, vd một cái gì đó như:

writer.addpages(PdfReader(inpfn).pages[:-1]) 

Tuyên bố từ chối trách nhiệm: Tôi là tác giả chính pdfrw.

1

Hợp nhất tất cả các tệp pdf có trong thư mục

Đặt tệp pdf vào thư mục. Khởi động chương trình. Bạn nhận được một pdf với tất cả các tệp PDF được hợp nhất.

import os 
from PyPDF2 import PdfFileMerger 

x = [a for a in os.listdir() if a.endswith(".pdf")] 

merger = PdfFileMerger() 

for pdf in x: 
    merger.append(open(pdf, 'rb')) 

with open("result.pdf", "wb") as fout: 
    merger.write(fout) 
Các vấn đề liên quan