【发布时间】:2019-10-02 15:50:29
【问题描述】:
我的目标是从网站中提取多个 PDF 页面,使它们在自己的查看器中可用,并将它们合并到一个 PDF 文件中,保持原始顺序。因此,我使用tempfile 库将每个提取的页面保存到一个临时目录中:
def save_publication_page_to_tempfile(
publication_page,
page_number,
directory
):
temp_pdf = tempfile.NamedTemporaryFile(
prefix=f'{page_number}_',
suffix='.pdf',
dir=directory,
delete=False
)
temp_pdf.write(publication_page)
return temp_pdf.name
保存每个提取的页面后,使用pdftk 工具合并文件:
def merge_pdf_files(self, publication_metadata, output_filename):
with tempfile.TemporaryDirectory() as temp_dir:
for publication in publication_metadata:
save_publication_page_to_tempfile(
publication['content'],
publication['page_number'],
temp_dir
)
command = (
f"pdftk $(ls {temp_dir}/* | sort -n -t _ -k 1) "
f"cat output {os.path.join('/tmp', output_filename)}"
)
os.system(command)
if os.path.exists(os.path.join('/tmp', output_filename)):
return os.path.join('/tmp', output_filename)
else:
return None
但是,合并完成并没有遵循所需的顺序。我注意到,当我在转换命令之前使用pdb.set_trace () 停止执行,然后直接在使用的目录中执行相同的命令时,生成的 PDF 遵循所需的顺序:
pdftk $(ls * | sort -n -t _ -k 1) cat output result.pdf
最后,我想知道一些可能的原因,为什么生成的 PDF 在 PDF 文件所在的临时目录中比较 Python 脚本执行和 BASH 命令执行顺序不同。
【问题讨论】:
标签: python python-3.x bash pdftk