Work with Images in PDF via Python

Manipulate images in PDF document. Use Aspose.PDF for Python for .NET to modify PDF documents programmatically

Most popular action with Images in Python

Add Image to PDF Document Using Python Library

In order to add Image in PDF, we’ll use Aspose.PDF for .NET API which is a feature-rich, powerful and easy to use document manipulation API for python-net platform. Open NuGet package manager, search for Aspose.PDF and install. You may also use the following command from the Package Manager Console.

Python Package Manager Console

pip install aspose-pdf

Add Image to PDF via Python


You need Aspose.PDF for Python to try the code in your environment.

  1. Create a Document object and open the input PDF document.
  2. Get the page you want to add an image.
  3. Add the image into the page’s Resources collection.
  4. Use the GSave operator to save the current graphical state.
  5. Use ConcatenateMatrix operator to specify where the image is to be placed.
  6. Use the Do operator to draw the image on the page.
  7. Use GRestore operator to save the updated graphical state.
  8. Save the PDF file.

Add Image in an Existing PDF File - Python

Example: Python

    import aspose.pdf as ap 
   
    input_file = DIR_INPUT + "sample.pdf"
    output_pdf = DIR_OUTPUT + "add_image.pdf"
    image_file = DIR_INPUT + "logo.jpg"
    # Open document
    document = ap.Document(input_file)

    document.pages[1].add_image(image_file, ap.Rectangle(20, 730, 120, 830, True))

    document.save(output_pdf)