簡體   English   中英

如何使用 PyPDF2 pdfmerger 在文件之間插入空白頁

[英]How do I insert a blank page between files using PyPDF2 pdfmerger

我正在使用此腳本合並賬單文件,以便打印 1 個文件。 賬單是 3 頁,所以我需要在每個文件之后插入一個空白頁,這樣下一張賬單的第一頁就不會打印在前一張賬單的背面。 如何在每個賬單文件的循環每次迭代后插入空白頁?

# If the file errors with "no module PyPDF2" then from command line, run pip install PyPDF2

import os
from os import listdir,mkdir,startfile
from os.path import isfile, join,exists
from PyPDF2 import PdfFileMerger

#Input file path and print the pdf files in that path
path = input("Enter the folder location: ")
pdffiles = [f for f in listdir(path) if isfile(join(path, f)) and '.pdf' in f]
print('\nList of PDF Files:\n')
for file in pdffiles:
    print(file)

#Input the name of the result file
resultFile = input("\nEnter the name of the result file : ")
if '.pdf' not in resultFile:
    resultFile += '.pdf'

#Append the pdf files
merger = PdfFileMerger()
for pdf in pdffiles:
    merger.append(path+'\\'+pdf)
    # The line below hopefully will add a blank page between 
    merger.addBlankPage(w,h)

#If the Output directory does not exist then create one
if not exists(path+'\\Output'):
    mkdir(path+'\\Output')

#Write the merged result file to the Output directory
merger.write(path+'\\Output\\'+resultFile)
merger.close()

#Launch the result file
print('\n'+resultFile,'Successfully created!!! at ',path+'\\Output\\')
startfile(path+'\\Output\\'+resultFile)

首先將空白頁添加到末尾,然后將它們合並。

import os
from PyPDF2 import PdfFileMerger, PdfFileReader, PdfFileWriter


def add_blank_to_end(files: list) -> list:
    names = []
    for f in files:
        pdf_in = open(f, 'rb')
        pdf_file = PdfFileReader(pdf_in)
        output = PdfFileWriter()
        output.appendPagesFromReader(pdf_file)
        output.addBlankPage()
        names.append(f'b{f}')
        outputStream = open(f'b{f}', 'wb')
        output.write(outputStream)
    return names


def merge_pdfs(files: list):
    merger = PdfFileMerger()
    for f in files:
        merger.append(f)
    merger.write("document-output.pdf")


files = ['file1.pdf', 'file2.pdf']
with_blank = add_blank_to_end(files)
merge_pdfs(with_blank)

# delete extra files
for i in with_blank:
    os.remove(i)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM