簡體   English   中英

Python轉換PDF

[英]Python converting PDF

我有以下代碼,可以從一個多頁PDF中創建多個jpg。 但是,我收到以下錯誤: wand.exceptions.BlobError: unable to open image '{uuid}.jpg': No such file or directory @ error/blob.c/OpenBlob/2841但是圖像已創建。 最初我以為可能是比賽條件,所以我輸入了time.sleep()但是那也不起作用,所以我不相信就是這樣。 誰看過這個嗎?

def split_pdf(pdf_obj, step_functions_client, task_token):
    print(time.time())

    read_pdf = PyPDF2.PdfFileReader(pdf_obj)
    images = []

    for page_num in range(read_pdf.numPages):
        output = PyPDF2.PdfFileWriter()
        output.addPage(read_pdf.getPage(page_num))

        generateduuid = str(uuid.uuid4())
        filename = generateduuid + ".pdf"
        outputfilename = generateduuid + ".jpg"
        with open(filename, "wb") as out_pdf:
            output.write(out_pdf) # write to local instead

        image = {"page": str(page_num + 1)}  # Start at 1 rather than 0

        create_image_process = subprocess.Popen(["gs", "-o " + outputfilename, "-sDEVICE=jpeg", "-r300", "-dJPEGQ=100", filename], stdout=subprocess.PIPE)
        create_image_process.wait()

        time.sleep(10)
        with(Image(filename=outputfilename)) as img:
            image["image_data"] = img.make_blob('jpeg')
            image["height"] = img.height
            image["width"] = img.width
            images.append(image)

            if hasattr(step_functions_client, 'send_task_heartbeat'):
                step_functions_client.send_task_heartbeat(taskToken=task_token)

    return images

嘗試首先打開PDF時,似乎沒有傳遞值-因此,您收到的錯誤。

確保使用完整的文件路徑格式化字符串,例如f'/path/to/file/{uuid}.jpg''/path/to/file/{}.jpg'.format(uuid)

我真的不明白為什么要使用PyPDF2,GhostScript和魔杖。 您無需解析/操作任何PostScript,並且Wand位於ImageMagick的頂部,而ImageMagick則位於ghostscript的頂部。 您也許可以將功能縮減為一個PDF實用程序。

def split_pdf(pdf_obj, step_functions_client, task_token):
    images = []
    with Image(file=pdf_obj, resolution=300) as document:
        for index, page in enumerate(document.sequence):
            image = {
                "page": index + 1,
                "height": page.height,
                "width": page.width,
            }
            with Image(page) as frame:
                image["image_data"] = frame.make_blob("JPEG")
            images.append(image)
            if hasattr(step_functions_client, 'send_task_heartbeat'):
                step_functions_client.send_task_heartbeat(taskToken=task_token)
    return images

最初我以為可能是比賽條件,所以我輸入了time.sleep(),但是那也不起作用,所以我不相信就是這樣。 誰看過這個嗎?

該示例代碼沒有任何錯誤處理。 PDF可以由許多軟件供應商生成,並且它們中的許多工作都很草率。 PyPDF或Ghostscript失敗的可能性很大,而您再也沒有機會解決這個問題。

例如,當我將Ghostscript用於隨機網站生成的PDF時,我經常在stderr上看到以下消息...

ignoring zlib error: incorrect data check

...導致文檔不完整或空白頁。

另一個常見的示例是系統資源已用盡,無法分配額外的內存。 Web服務器一直在發生這種情況,解決方案通常是將任務遷移到隊列工作器,該工作器可以在每次任務完成時徹底關閉。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM