DEV Community

Free Python Code
Free Python Code

Posted on

how to convert any html page to image using Python and imgkit

Hi πŸ™‚πŸ–

Introduction

In this tutorial, we will learn how to convert any HTML page to an image using Python and imgkit. imgkit is a Python library that allows you to convert HTML to PNG, or JPG images. It uses the wkhtmltopdf library to render the HTML to a PDF, and then converts the PDF to an image using the ImageMagick library.

Installing the imgkit library
pip install imgkit

Install wkhtmltopdf

Debian/Ubuntu:

sudo apt-get install wkhtmltopdf
Warning! Version in debian/ubuntu repos have reduced functionality (because it compiled without the wkhtmltopdf QT patches), such as adding outlines, headers, footers, TOC etc. To use this options you should install static binary from wkhtmltopdf site or you can use this script.

MacOSX:

brew install --cask wkhtmltopdf

Windows and other options:

Go to : https://wkhtmltopdf.org/
click on Download a precompiled binary

Image description

Choose what is right for your computer

Image description

install wkhtmltopdf

Image description

You can add wkhtmltopdf to the system environment path, but I want to make it as easy as possible.

If you want to add wkhtmltopdf to the system environment path:

https://www.architectryan.com/2018/03/17/add-to-the-path-on-windows-10/

Convert HTML file to Image from file

import imgkit

path_wkthmltoimage = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltoimage.exe'
config = imgkit.config(wkhtmltoimage=path_wkthmltoimage)

imgkit.from_file('index.html', 'out.jpg', config = config)

Enter fullscreen mode Exit fullscreen mode

result

Image description

Convert page from url to Image from file

import imgkit

path_wkthmltoimage = r'C:\Program Files\wkhtmltopdf\bin\wkhtmltoimage.exe'
config = imgkit.config(wkhtmltoimage=path_wkthmltoimage)
imgkit.from_url('https://pypi.org/', 'out.jpg', config = config)


Enter fullscreen mode Exit fullscreen mode

result

Image description

Conclusion

In this tutorial, we learned how to convert any HTML page to an image using Python and imgkit. imgkit is a powerful tool that can be used to create images from HTML pages.

Now we're done πŸ€—

Don't forget to like and follow πŸ™‚

Support me on PayPal πŸ€—
https://www.paypal.com/paypalme/amr396

Top comments (0)