Converting Images to PDF by Python img2pdf without Removing Image Alpha Channel – Python PDF Processing

By | June 13, 2020

When you are using python img2pdf library to convert some images to pdf, you may fail to convert if there exists alpha channel in images. In this tutorial, we will introduce you how to convert these images with alpha channel to pdf.

Converting images with alpha channel to pdf

Usually, in order to convert images with alpha channel, we can remove these alpha channel using ImageMagick first, then convert them using img2pdf. Here is an example:

Python Detect and Remove Image Alpha Channel with ImageMagick Wand – Python Wand Tutorial

Meanwhile, we also can use another python pdf library (pymupdf) to convert images with alpha channel to a new pdf. Here is an tutorial.

A Simple Guide to Python Convert Image to PDF without Removing Image Alpha Channel Using PyMuPDF

Both of them can covnert images with alpha channel to pdf. In this tutorial, we will introduce a new way to convert. You can do by following steps below:

Convert images to webp image

Webp imaegs are very small, we can convert png, jpg images to webp. Then convert these images to pdf using img2pdf, which can reduce the size of pdf. For example, if you use pymupdf to convert images to pdf, the size of converted pdf is much larger than the total size of all images, which is not a good choice.

In order to convert images to webp in python, we can read this tutorial.

Best Practice to Python Convert PNG to WebP with Pillow – Python Pillow Tutorial

Convert webp images to img2pdf

After we have convertd images to webp, we can convert these images to pdf using python img2pdf easily.

For example:

import img2pdf

images = ['1.webp', '2.webp']
with open('test.pdf',"wb") as f:
        f.write(img2pdf.convert(images))

Leave a Reply