pythonpdf

How can I change/modify/replace text in a PDF using Python?


I have a PDF file and I want to replace some text within the PDF file and generate new PDF file. How can I do that in Python?


Solution

  • You can try Aspose.PDF Cloud SDK for Python, Aspose.PDF Cloud is a REST API PDF Processing solution. It is paid API and its free package plan provides 50 credits per month.

    I'm developer evangelist at Aspose.

    import os
    import asposepdfcloud
    from asposepdfcloud.apis.pdf_api import PdfApi
    
    # Get App key and App SID from https://cloud.aspose.com
    pdf_api_client = asposepdfcloud.api_client.ApiClient(
        app_key='xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx',
        app_sid='xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxxxx')
    
    pdf_api = PdfApi(pdf_api_client)
    filename = '02_pages.pdf'
    remote_name = '02_pages.pdf'
    copied_file= '02_pages_new.pdf'
    #upload PDF file to storage
    pdf_api.upload_file(remote_name,filename)
    
    #upload PDF file to storage
    pdf_api.copy_file(remote_name,copied_file)
    
    #Replace Text
    text_replace = asposepdfcloud.models.TextReplace(old_value='origami',new_value='polygami',regex='true')
    text_replace_list = asposepdfcloud.models.TextReplaceListRequest(text_replaces=[text_replace])
    
    response = pdf_api.post_document_text_replace(copied_file, text_replace_list)
    print(response)