Convert Image to PDF in Python

PDF is one of the ruling file formats, which is primarily used for sharing and printing documents. Often, you prefer to convert the documents/files of different formats to PDF before sharing. In specific cases, you need to convert PNG, JPG, and other images to PDF format programmatically. To achieve that, this article covers how to convert an image to a PDF in Python. You will also learn about the conversion of multiple images to a single PDF.

How to Convert Image to PDF in Python

To convert images to PDF, we will use Aspose.Words for Python. It is a powerful and feature-rich library that offers a high-fidelity conversion of files into various popular formats. Also, it provides a free utility to generate PDFs from images.

You can install the library from PyPI using the following pip command.

> pip install aspose-words

Save an Image as PDF in Python

The following are the steps to convert an image to a PDF file in Python.

  • First, create a new document using Document class.
  • Then, create a DocumentBuilder object and initialize it with the Document object.
  • Insert image into the document using DocumentBuilder.insert_image(fileName) method.
  • Finally, save the PDF document using Document.save(fileName) method.

The following code sample shows how to convert a PNG image to a PDF in Python.

Convert Multiple Images to a PDF in Python

The following are the steps to convert multiple images to a single PDF file in Python.

  • First, create a new document using Document class.
  • Then, create a DocumentBuilder object and initialize it with the Document object.
  • Get the list of the image files from the desired folder.
  • Loop through the list of the image files and insert each image into the document using DocumentBuilder.insert_image(fileName) method.
  • Finally, save the PDF document using Document.save(fileName) method.

The following code sample shows the conversion of multiple images to a single PDF in Python.

Free Image to PDF Converter

You can convert images to PDF without evaluation limitations by getting a free temporary license.

Explore Image to PDF Conversion Library

You can explore more about Aspose.Words for Python using documentation. In case you would have any queries, feel free to let us know via our forum.

Conclusion

In this article, you have learned how to convert an image to PDF format in Python. Also, you have seen how to convert multiple images to a single PDF programmatically. You can easily integrate the provided code samples into your application and perform the image-to-PDF conversion.

See Also