Python

Code Examples

# used python3.11 Test
import requests
import sys
import time

app_key = "sk-xxxxxx"
convert_api = "https://api.pdf2document.com/api/v1/pdf2doc/convertapi"
convert_status_api = "https://api.pdf2document.com/api/v1/pdf2doc/convertapi/{}"


def pdf_convert_api(pdfUrl):
    headers = {
        "APPKEY": app_key,
        "Content-Type": "application/json",
    }
    data = {
        "pdf_url":  pdfUrl,
    }
    response = requests.post(convert_api, headers=headers, json=data)
    if response.status_code == 200:
        convert_id = response.json().get('data', {}).get('convert_id')
        print(f"Conversion started with ID: {convert_id}")
        return convert_id
    else:
        print(f"Error: {response.status_code}")
        return None


def get_convert_status(convert_id):
    headers = {
        "APPKEY": app_key,
        "Content-Type": "application/json",
    }
    response = requests.get(convert_status_api.format(convert_id), headers=headers)
    if response.status_code == 200:
        data = response.json().get('data', {})
        status = data.get('status')
        if status == "doing":
            print("Please wait while the transfer is underway...")
            time.sleep(60)  # Wait for 1 minute before checking again
            get_convert_status(convert_id)
        elif status == "success":
            word_url = data.get('word_url')
            print(f"The conversion is complete, and the download link for the file is: {word_url}")
        else:
            print("Conversion failed or is in an unknown state.")
    else:
        print(f"Error: {response.status_code}")


if __name__ == "__main__":
    if len(sys.argv) < 2:
        print("Usage: python script.py [command] [args]")
        print("Commands:")
        print("  convert [pdfUrl]       Convert PDF to DOC  with the given pdfUrl")
        print("  status [ID]    Check conversion status with the given ID")
    elif sys.argv[1] == "convert" and len(sys.argv) == 3:
        pdf_convert_api(sys.argv[2])
    elif sys.argv[1] == "status" and len(sys.argv) == 3:
        get_convert_status(sys.argv[2])
    else:
        print("Invalid command or missing arguments")

Run

#run cmd: 
 python3.11 main.py convert https://www.w3.org/WAI/ER/tests/xhtml/testfiles/resources/pdf/dummy.pdf
#return task id
670555fab6776ae0982590a6

# Query the conversion status by task ID.
python3.11 main.py status 6703bfb4b6776ae09825909f
# Please follow the link below to indicate that the conversion was successful.
The conversion is complete, and the download link for the file is: https://api.pdf2document.com/api/v2/docx?md5_id=6703bfb4b6776ae09825909f