簡體   English   中英

通過 REST API 使用 Adob​​e PDF 服務將 PDF 轉換為 DOCX(在 Manjaro 中使用 Python)

[英]Convert a PDF to DOCX using Adobe PDF Services via REST API (with Python in Manjaro) Issues

我正在關注這個問題的答案: Convert a PDF to DOCX using Adob​​e PDF Services via REST API (with Python)以便能夠將 pdf 文檔導出為 docx 文檔。

我能夠成功獲取導出的文檔數據並將其保存到 docx 文件中。 問題是當我嘗試使用 LibreOffice 打開它時,它會顯示一條消息:

文件“test.docx”已損壞,因此無法打開。 LibreOffice 可以嘗試修復該文件。 損壞可能是由於數據傳輸造成的文檔操作或結構文檔損壞的結果。 我們建議您不要相信已修復文檔的內容。 本文檔禁止執行宏。

LibreOffice 應該修復文件嗎?r 文件。*

當我單擊“是”時,它抱怨說:

文件“test.docx”無法修復,因此無法打開。

然后關閉 LibreOffice。 我還應該說,我也嘗試使用 google docs 和 OneDrive 打開test.docx文件,但都無法打開該文件。 One Drive 顯示一條消息,內容如下:

無法打開此文檔進行編輯。

在這里,我添加了我正在使用的整個 python 腳本(我用占位符替換了敏感信息):

import requests
import json
import time

url = "https://cpf-ue1.adobe.io/ops/:create?respondWith=%7B%22reltype%22%3A%20%22http%3A%2F%2Fns.adobe.com%2Frel%2Fprimary%22%7D"

payload = {
    "cpf:engine": {
        "repo:assetId": "urn:aaid:cpf:Service-26c7fda2890b44ad9a82714682e35888"
    },
    "cpf:inputs": {
        "params": {
            "cpf:inline": {
                "targetFormat": "docx"
            }
    },
    "documentIn": {
        "dc:format": "application/pdf",
        "cpf:location": "InputFile0"
    }
    },
    "cpf:outputs": {
        "documentOut": {
            "dc:format": "application/vnd.openxmlformats-officedocument.wordprocessingml.document",
            "cpf:location": "/path_to_the_output_file/output.docx"
        }
    }
}

pdf_file = {"InputFile0": open('/path_to_the_pdf_file/mypdf.pdf','rb')}

headers = {
  'Authorization': 'Bearer My_bearer_tok',
  'Accept': 'application/json, text/plain, */*',
  'x-api-key': 'eb78dc9d04e54f10be1fd2189d91f8c9',
  'Prefer': 'respond-async,wait=0'
}

body = {"contentAnalyzerRequests": json.dumps(payload)}

response = requests.post(url=url, headers=headers, data=body, files=pdf_file)
print(response.text)
print(response.headers)
print(response.status_code)

time.sleep(5)

poll = True
while poll:
    new_request = requests.get(response.headers['location'], headers=headers)
    if new_request.status_code == 200:
        with open('test.docx', 'wb') as f:
            f.write(bytes(new_request.content))
        poll = False
    else:
        time.sleep(5)

在代碼的最后一部分,我還嘗試了有關如何保存文件的兩個建議:

with open('test.docx', 'wb') as f:
    f.write(new_request.content)
with open('test.docx', 'wb') as f:
    f.write(bytes(new_request.content))

但似乎沒有一個工作。 我還想評論一下,我能夠使用 Adob​​e 從他們的網頁手動將 pdf 轉換為 docx 並使用 LibreOffice 加載它,但我需要能夠自動執行此操作。

更新 1:我嘗試使用 Microsoft Word 從 Windows 筆記本電腦打開 docx 文件,它還抱怨文檔包含無法識別的信息,但最終能夠顯示 docx 文檔。

更新 2:也可以使用 python pdf2docx 包打開生成的 docx。

所以,歡迎任何關於可能發生的事情的想法(也許這是預期的行為),謝謝!

據我所知,您正在“按原樣”獲取響應並保存它,但響應實際上是一個多部分表單響應。 您必須先對其進行解析,並且其中包含數據的實際位。 多部分響應包括 json 信息 + 二進制文件,這就是您需要解析它的原因。

暫無
暫無

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

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