我從其他人的建議中編譯了以下腳本,但我似乎無法讓它正常運行。我需要將幾個 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, PdfFileReader, PdfFileWriter
#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)
def add_blank_to_end(pdffiles: list) -> list:
names = []
for f in pdffiles:
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
#Append the pdf files
def merge_pdfs(pdffiles: list):
merger = PdfFileMerger()
for f in pdffiles:
merger.append(f)
merger.write("document-output.pdf")
with_blank = add_blank_to_end(pdffiles)
merge_pdfs(with_blank)
uj5u.com熱心網友回復:
# 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, PdfFileReader, PdfFileWriter
#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)
def add_blank_to_end(pdffiles: list) -> list:
names = []
for f in pdffiles:
pdf_in = open(path '/' 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(pdffiles: list):
merger = PdfFileMerger()
for f in pdffiles:
merger.append(f)
merger.write("document-output.pdf")
with_blank = add_blank_to_end(pdffiles)
merge_pdfs(with_blank)
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/526482.html
標籤:Pythonpdf
