DEV Community

Allen Yang
Allen Yang

Posted on

How to Add QR Codes to PDFs with Python

In automated document generation, product labeling, or information distribution scenarios, it is often necessary to insert QR codes into PDF documents. QR codes can quickly store and transmit information, allowing users to access relevant content by scanning with their mobile phones. This article will introduce how to generate and insert QR codes into PDF documents using Python.

Environment Setup

First, you need to install the necessary Python libraries. This article uses Spire.PDF and Spire.Barcode libraries to handle PDF documents and generate QR code images.

pip install Spire.PDF
pip install Spire.Barcode
Enter fullscreen mode Exit fullscreen mode

Technical Approach

There are two main methods to insert QR codes into PDFs:

  1. Generate QR code image first, then insert it as an image into PDF - Use a barcode generation library to create a QR code PNG image, then embed it into the PDF page
  2. Draw QR code directly on the PDF canvas - Some libraries support drawing barcodes directly in the PDF graphics context

This article will demonstrate the first method, which is more flexible and easier to control the style and position of the QR code.

Generating QR Code Image

First, you need to create an independent QR code image file. The spire.barcode module makes it easy to generate various types of barcodes.

from spire.barcode import *

def WriteAllBytes(fname: str, data):
    """Write byte data to file"""
    with open(fname, "wb") as fp:
        fp.write(data)

# Create barcode settings object
barcodeSettings = BarcodeSettings()

# Set barcode type to QR code
barcodeSettings.Type = BarCodeType.QRCode

# Set the data contained in the QR code
barcodeSettings.Data = "https://example.com/product/12345"

# Create barcode generator
barCodeGenerator = BarCodeGenerator(barcodeSettings)

# Generate QR code image
barcodeImage = barCodeGenerator.GenerateImage()

# Save as PNG file
WriteAllBytes("QRCode.png", barcodeImage)
Enter fullscreen mode Exit fullscreen mode

Key API explanation for this code:

  • BarcodeSettings - Barcode configuration class used to set barcode type, data, color, and other properties
  • BarCodeType.QRCode - Specifies generating QR code type
  • BarCodeGenerator - Barcode generator that creates images based on configuration
  • GenerateImage() - Returns byte data of the image

Inserting QR Code into PDF Document

After generating the QR code image, it can be added to the PDF page as an image stamp. Here is the complete implementation code:

from spire.pdf import *
from spire.barcode import BarcodeSettings, BarCodeType, BarCodeGenerator

def WriteAllBytes(fname: str, data):
    with open(fname, "wb") as fp:
        fp.write(data)

# Generate QR code
barcodeSettings = BarcodeSettings()
barcodeSettings.Type = BarCodeType.QRCode
barcodeSettings.Data = "https://example.com/product/12345"
barcodeSettings.ShowText = False
barcodeSettings.ImageHeight = 230.0
barcodeSettings.ImageWidth = 230.0
barcodeSettings.LeftMargin = 1.0
barcodeSettings.TopMargin = 1.0
barcodeSettings.RightMargin = 1.0
barcodeSettings.BottomMargin = 1.0

barCodeGenerator = BarCodeGenerator(barcodeSettings)
barcodeImage = barCodeGenerator.GenerateImage()
WriteAllBytes("temp_qrcode.png", barcodeImage)

# Create PDF document
doc = PdfDocument()
doc.PageSettings.Size = PdfPageSize.A4()
page = doc.Pages.Add()

# Load QR code image
qrcode = PdfImage.FromFile("temp_qrcode.png")

# Define position and size rectangle for QR code - fixed at left side of page
qrcode_width = float(qrcode.Width)
qrcode_height = float(qrcode.Height)
page_width = page.Size.Width
page_height = page.Size.Height

# Calculate QR code position: fixed at 100 points from left boundary, 150 points from top
stampRect = RectangleF(
    PointF(100.0, 150.0),
    SizeF(qrcode_width, qrcode_height)
)

# Create rubber stamp annotation
loStamp = PdfRubberStampAnnotation(stampRect)

# Create appearance object
loAppearance = PdfAppearance(loStamp)

# Create template and draw QR code in it
template = PdfTemplate(stampRect.Width, stampRect.Height)
template.Graphics.DrawImage(qrcode, 0.0, 0.0, float(qrcode.Width), float(qrcode.Height))

# Set appearance and add to page annotation collection
loAppearance.Normal = template
loAppearance.MouseHover = template
loAppearance.Pressed = template
loStamp.Appearance = loAppearance
page.AnnotationsWidget.Add(loStamp)

# Add descriptive text - at appropriate distance below QR code
font = PdfTrueTypeFont("Arial", 12.0, PdfFontStyle.Regular, True)
brush = PdfBrushes.get_Black()
text_y_position = stampRect.Y + stampRect.Height + 20.0  # 20 points spacing from QR code bottom
page.Canvas.DrawString("Scan QR code to get product details", font, brush, stampRect.X, text_y_position)

# Save document
doc.SaveToFile("ProductWithQRCode.pdf")
doc.Close()
Enter fullscreen mode Exit fullscreen mode

Insertion Result Preview

Generate QR code with Python and insert into PDF document

Code Analysis

QR Code Position Control

RectangleF(PointF(x, y), SizeF(width, height)) defines the position and size of the QR code on the PDF page:

  • PointF(100.0, 150.0) - QR code top-left corner coordinates, origin located at page bottom-left corner
  • SizeF(qrcode_width, qrcode_height) - Width and height of QR code (in points, 1 point ≈ 1/72 inch)

Drawing Image Directly on Canvas

Besides using the annotation method, you can also draw the QR code image directly on the PDF canvas:

from spire.pdf.common import *
from spire.pdf import *
from spire.barcode import *

def WriteAllBytes(fname: str, data):
    with open(fname, "wb") as fp:
        fp.write(data)

# Generate QR code
barcodeSettings = BarcodeSettings()
barcodeSettings.Type = BarCodeType.QRCode
barcodeSettings.Data = "https://example.com/contact"
barCodeGenerator = BarCodeGenerator(barcodeSettings)
barcodeImage = barCodeGenerator.GenerateImage()
WriteAllBytes("contact_qr.png", barcodeImage)

# Create PDF and draw directly
doc = PdfDocument()
page = doc.Pages.Add()

# Load image
qrcode = PdfImage.FromFile("contact_qr.png")

# Draw image directly at specified position on canvas
page.Canvas.DrawImage(qrcode, 50.0, 50.0, 120.0, 120.0)

# Add title
font = PdfFont(PdfFontFamily.Helvetica, 16.0, PdfFontStyle.Bold)
page.Canvas.DrawString("Contact Us", font, PdfBrushes.get_Black(), 50.0, 180.0)

doc.SaveToFile("ContactCard.pdf")
doc.Close()
Enter fullscreen mode Exit fullscreen mode

This method is simpler and more direct, suitable for scenarios that don't require interactive features.

Customizing QR Code Style

You can customize the QR code appearance by adjusting properties of BarcodeSettings:

barcodeSettings = BarcodeSettings()
barcodeSettings.Type = BarCodeType.QRCode
barcodeSettings.Data = "Custom styled QR code"

# Set foreground and background colors
barcodeSettings.ForeColor = Color.get_Black()
barcodeSettings.BackColor = Color.get_White()

# Set image width (affects resolution)
barcodeSettings.ImageWidth = 300

# Set margins
barcodeSettings.MarginTop = 10
barcodeSettings.MarginBottom = 10
barcodeSettings.MarginLeft = 10
barcodeSettings.MarginRight = 10

barCodeGenerator = BarCodeGenerator(barcodeSettings)
barcodeImage = barCodeGenerator.GenerateImage()
Enter fullscreen mode Exit fullscreen mode

Practical Tips

Batch Generate PDFs with QR Codes

When you need to generate PDFs with different QR codes for multiple products, you can use loop processing:

products = [
    {"id": "P001", "url": "https://example.com/p1"},
    {"id": "P002", "url": "https://example.com/p2"},
    {"id": "P003", "url": "https://example.com/p3"}
]

for product in products:
    # Generate QR code
    barcodeSettings.Data = product["url"]
    # ... Generate image and PDF
    doc.SaveToFile(f"Product_{product['id']}.pdf")
Enter fullscreen mode Exit fullscreen mode

Adjusting QR Code Clarity

If higher print quality is required, you can increase the resolution of the QR code image:

barcodeSettings.ImageWidth = 600  # Increase width to improve resolution
barcodeSettings.DPI = 300         # Set 300 DPI suitable for printing
Enter fullscreen mode Exit fullscreen mode

Summary

This article introduces the complete process of inserting QR codes into PDF documents using Python:

  1. Use spire.barcode to generate QR code images
  2. Use spire.pdf to create or load PDF documents
  3. Load QR code images using PdfImage.FromFile()
  4. Draw QR code to specified position using DrawImage() method

This method is suitable for various scenarios such as product labels, promotional materials, contact cards, etc. By adjusting position and size parameters, you can precisely control the layout of QR codes on the page to meet different design requirements.

Top comments (0)