Best Practice to Python Convert PNG to PDF for Img2pdf Beginnners – Python Img2pdf Tutorial

By | July 22, 2019

In this tutorial, we will use python img2pdf library to convert a png image to pdf file. There exists some errors you must notice. You can fix these errors by reading our tutorials.

convert png to pdf

Preliminaries

1. Install img2pdf, ImageMagick and Wand

Img2pdf and Wand

pip install img2pdf
pip install Wand

ImageMagick you should Install dll version.

The big error you may encounter

Refusing to work on images with alpha channel

To fix this error, you and read.

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

Define a function to remove alpha channel

def removeAlpha(image_path):
    ok = False       
    with wand.image.Image(filename=image_path) as img:
        alpha = img.alpha_channel
        if not alpha:
            ok = True
            return ok
        try:
            img.alpha_channel = 'remove' #close alpha channel   
            img.background_color = wand.image.Color('white')        
            img.save(filename=image_path)
            ok = True
        except:
            ok = False
    return ok

Define a function to convert png to pdf

def convert_png_to_pdf(image_path, pdf_path):
    ok = False
    if not removeAlpha(image_path):
        print("fail to remove alpha channel")
        return False
    try:
        pdf_bytes = img2pdf.convert(image_path) 
        file = open(pdf_path, "wb") 
    
        # writing pdf files with chunks 
        file.write(pdf_bytes)  
        file.close()
        ok = True
    except:
        ok = False
    return ok

How to use?

Here is an example.

convert_status = convert_png_to_pdf(image_path='E:\\ts.png', pdf_path = 'ts3.pdf')
if convert_status:
    print("convert png to pdf successfully!")
else:
    print("fail to convert png to pdf!")

Leave a Reply