In order to take and covert a screenshot to PDF, firstly the PyAutoGUI can be used which is an automation library in python which can control mouse, keyboard and can handle many GUI control tasks. Secondly, for the conversion PIL(Python Imaging Library) of python can be used which provides image processing facility and it supports many file formats and their conversion. The second library which can be used for conversion is img2pdf which provides as the name suggests the lossless and faster conversion of image to pdf.
For installation of the library use the following commands:
pip install PyAutoGUI
- PIL(Python imaging library):
pip install Pillow
pip install img2pdf
In this approach, we are using the PIL library of python. First, the screenshot is taken using the screenshot() function of PyAutoGUI library of python. After that, the output of the screenshot is saved. The open() method of PIL library is used to open the image and then convert() method to convert the image to RGB which is then saved with .pdf extension in the given path. Alternatively, you can also provide the screenshot/image by providing the path inside the open() method.
Note: The r’ is used so that the string is treated as a raw string.
In this approach, the img2pdf library is used for the conversion. Firstly, the screenshot is taken using the screenshot() method of PyAutoGUI library of python. After the screenshot is opened using the open() method and “rb” as a parameter is passed for opening the file in the binary format. After that, the output file which is pdf is opened using open() method bt passing the “wb” parameter (used for writing in binary). The write() function is called and convert() method of img2pdf is passed with screenshot object. At last, both objects are closed so that they flush any unwritten information.
The main advantage to the method is that it is fast as compared to PIL and it is also lossless conversion with small size. Alternatively, you can also provide the screenshot/image by providing the path inside the open() method.
Note: The screenshot/image does not contain an alpha channel since there is no method available that converts the RGBA to RGB in img2pdf.
Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.
To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course.