【问题标题】:PFTK command called by Python does not work properlyPython 调用的 PFTK 命令无法正常工作
【发布时间】: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


    【解决方案1】:

    save_publications_to_tempfile 的以下更改解决了我的问题:

    def save_publication_page_to_tempfile(
        publication_page,
        page_number,
        directory
    ):
        formatted_page_number = str(page_number).zfill(6)
        temp_pdf = tempfile.NamedTemporaryFile(
            prefix=f'{formatted_page_number}_',
            suffix='.pdf',
            dir=directory,
            delete=False
        )
        temp_pdf.write(publication_page)
    
        return temp_pdf.name    
    

    【讨论】:

      猜你喜欢
      • 2022-10-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-01-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多