首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Python脚本将PDF文件与空白页合并

Python脚本将PDF文件与空白页合并
EN

Stack Overflow用户
提问于 2022-11-01 19:49:39
回答 1查看 23关注 0票数 1

下面的脚本是根据其他人的建议编写的,但我似乎无法让它正常运行。我需要将几个3页的票据文件合并到一个文件中,以便打印,同时在每个票据文件之间添加一个空白页,以便每个账单正确打印(我们不希望在上一张账单的背面打印一张钞票的第一页)。

代码语言:javascript
复制
# 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)
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-11-01 20:16:07

代码语言:javascript
复制
# 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)
票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74281106

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档