Screenshot to PDF using Python (example included)

In this tutorial, you’ll see the complete steps to take a screenshot and then convert it to PDF using Python.

To accomplish this goal you’ll need to use the following packages:

  • pyautogui
  • pillow (pil)

Steps to take a screenshot and then convert it to PDF using Python

Step 1: Install the relevant packages

If you haven’t already done so, install the pyautogui package using the command below:

pip install pyautogui

Note that depending on your version of pip, you may run into an issue with the installation of pyautogui.

Next, install the Pillow (PIL) package using this command:

pip install Pillow

Step 2: Take the screenshot and then convert it to PDF

You can use the following template to assist you in taking the screenshot and converting it to PDF using Python:

import pyautogui
from PIL import Image

myScreenshot = pyautogui.screenshot()
screenshotPath = r'path to save screenshot\file name.png'
myScreenshot.save(screenshotPath)

image1 = Image.open(screenshotPath)
im1 = image1.convert('RGB')
pdfPath = r'path where the pdf will be stored\new file name.pdf'
im1.save(pdfPath)

In the above code, you’ll need to make sure to specify:

  • The ‘path to save screenshot\file name.png
  • The ‘path where the pdf will be stored\new file name.pdf

For example, in my case:

  • The ‘path to save screenshot\file name.png‘ = ‘C:\Users\Ron\Desktop\Test\myScreenshot.png’
  • The ‘path where the pdf will be stored\new file name.pdf‘ = ‘C:\Users\Ron\Desktop\Test\myPdf.pdf’

So for this example, the complete Python code to take the screenshot and then convert it to PDF is as follows:

import pyautogui
from PIL import Image

myScreenshot = pyautogui.screenshot()
screenshotPath = r'C:\Users\Ron\Desktop\Test\myScreenshot.png'
myScreenshot.save(screenshotPath)

image1 = Image.open(screenshotPath)
im1 = image1.convert('RGB')
pdfPath = r'C:\Users\Ron\Desktop\Test\myPdf.pdf'
im1.save(pdfPath)

Don’t forget to place “r” before the paths to avoid any errors when running the code.

Once you run the above code (adjusted to your paths), you’ll see the screenshot file (png), as well as the PDF file:

Screenshot to PDF using Python

Optionally, you could enhance the code to keep only the PDF file after taking the screenshot. In that case, the screenshot will be deleted once the PDF file is saved at your specified location.

Here is the modified template that you may use:

import pyautogui
from PIL import Image
import os

myScreenshot = pyautogui.screenshot()
screenshotPath = r'path to save screenshot\file name.png'
myScreenshot.save(screenshotPath)

image1 = Image.open(screenshotPath)
im1 = image1.convert('RGB')
pdfPath = r'path where the pdf will be stored\new file name.pdf'
im1.save(pdfPath)

os.remove(screenshotPath)

Note that for the above code, you’ll need to use the os package in order to remove the screenshot (png file) once the PDF file is created.