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

By | August 2, 2019

To convert images to pdf file, you may use python img2pdf library, however, you may find Error: Refusing to work on images with alpha channel. To fix this error, you have to use Wand and ImageMagick to remove alpha channel.

Fix Error: Refusing to work on images with alpha channel Using img2pdf – img2pdf Tutorial

In this tutorial, we will introduce a new way to convert images to pdf without processing alpha channel.

Preliminaries

pip install PyMuPDF

Import python libraries

import sys, fitz

Prepare a png image containing alpha channel

imglist=['e:\\ts.png']

Convert this image to pdf

doc = fitz.open()                            # PDF with the pictures
for i, f in enumerate(imglist):
    img = fitz.open(f) # open pic as document
    rect = img[0].rect                       # pic dimension
    pdfbytes = img.convertToPDF()            # make a PDF stream
    img.close()                              # no longer needed
    imgPDF = fitz.open("pdf", pdfbytes)      # open stream as PDF
    page = doc.newPage(width = rect.width,   # new page with ...
                       height = rect.height) # pic dimension
    page.showPDFpage(rect, imgPDF, 0) 
           # image fills the page
doc.save("e:\\all-my-pics.pdf")

In this example, we use a python list to save image path, which means we can convert some images to one pdf once.

2 thoughts on “A Simple Guide to Python Convert Image to PDF without Removing Image Alpha Channel

Leave a Reply