Saving PDF page as image with Python

I am going to show a simple solution to print a specific pfd page as image. For this, we are going to use the library fitz . This library is very easy to use and we are going to need only a few lines of code:

import fitz

doc = fitz.open(path_to_pdf)

zoom_x = 3  
zoom_y = 3  
mat = fitz.Matrix(zoom_x, zoom_y) 

page_index = 0
pix = doc[page_index].getPixmap(matrix=mat)

We can write this matrix to a file:

filename = 'output.png'
pix.writePNG(filename)

Or load into opencv:

import cv2
import numpy as np

img = np.asarray(bytearray(pix.getImageData('png')), dtype="uint8")
img = cv2.imdecode(img, cv2.IMREAD_COLOR)

I hope you enjoyed this tip!!