gpt4 book ai didi

python - 合并两个 PDF

转载 作者:太空狗 更新时间:2023-10-30 01:21:56 24 4
gpt4 key购买 nike

import PyPDF2 
import glob
import os
from fpdf import FPDF
import shutil

class MyPDF(FPDF): # adding a footer, containing the page number
def footer (self):
self.set_y(-15)
self.set_font("Arial", Style="I", size=8)
pageNum = "page %s/{nb}" % self.page_no()
self.cell(0,10, pageNum, align="C")


if __name__ == "__main__":
os.chdir("pathtolocation/docs/") # docs location
os.system("libreoffice --headless --invisible --convert-to pdf *") # this converts everything to pdf
for file in glob.glob("*"):
if file not in glob.glob("*.pdf"):
shutil.move(file,"/newlocation") # moving files we don't need to another folder

# adding the cover and footer
path = open(file, 'wb')
path2 = open ('/pathtocover/cover.pdf')
merger = PyPDF2.PdfFileMerger()
pdf = MyPDF()

for file in glob.glob("*.pdf"):
pdf.footer()
merger.merge(position=0, fileobj=path2)
merger.merge(position=0, fileobj=path)
merger.write(open(file, 'wb'))

此脚本转换为 pdf,为 pdf 添加封面和包含页码的页脚,修复了一些东西,现在我最后一次运行它以查看它是否正常工作,它花费了太多时间,没有错误,确实我做错了什么,或者合并和添加页脚需要那么长时间吗?我正在处理 3 个文件,它转换它们的速度非常快。

异常输出

convert /home/projects/convert-pdf/docs/sample (1).doc ->
/home/projects/convert-pdf/docs/sample (1).pdf using writer_pdf_Export

所以它正在转换和移动,我认为问题出在这里

   for file in glob.glob("*.pdf"):
pdf.footer()
merger.merge(position=0, fileobj=path2)
merger.merge(position=0, fileobj=path)
merger.write(open(file, 'wb'))

因为我正在尝试将 position=0position=0 合并,所以不确定

最佳答案

这实际上作为评论更好,但我想展示代码。您需要在其中添加一些 try block 以捕获任何错误 - 这是您可以做的非常基本的事情。

import PyPDF2 
import glob
import os
from fpdf import FPDF
import shutil

class MyPDF(FPDF): # adding a footer, containing the page number
def footer (self):
try:
self.set_y(-15)
self.set_font("Arial", Style="I", size=8)
pageNum = "page %s/{nb}" % self.page_no()
self.cell(0,10, pageNum, align="C")
except Exception, err:
print "Error applying footer: {}".format(err)


if __name__ == "__main__":

try:
os.chdir("pathtolocation/docs/") # docs location
os.system("libreoffice --headless --invisible --convert-to pdf *") # this converts everything to pdf
for file in glob.glob("*"):
if file not in glob.glob("*.pdf"):
shutil.move(file,"/newlocation") # moving files we don't need to another folder

# adding the cover and footer
path = open(file, 'wb')
path2 = open ('/pathtocover/cover.pdf')
merger = PyPDF2.PdfFileMerger()
pdf = MyPDF()
except Exception, err:
print "error setting up the pdf: {}".format(err)

for file in glob.glob("*.pdf"):
try:
pdf.footer()
merger.merge(position=0, fileobj=path2)
merger.merge(position=0, fileobj=path)
merger.write(open(file, 'wb'))
except Exception, err:
print "Error processing glob: {}".format(err)

关于python - 合并两个 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28115052/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com