Text as QR#
You have a text file. Split the text into a list (paragraphs, sentences, words). Generate a QR code for every item of the list and place it on it’s own page.
Show code cell source
import re
from fpdf import FPDF
import qrcode
from io import BytesIO
from PIL import Image
def create_qr_code(sentence):
qr = qrcode.QRCode(
version=1,
error_correction=qrcode.constants.ERROR_CORRECT_L,
box_size=10,
border=4,
)
qr.add_data(sentence)
qr.make(fit=True)
img = qr.make_image(fill='black', back_color='white')
return img
def title_page(pdf, title):
pdf.add_page()
img = create_qr_code(title)
img_bytes = BytesIO()
img.save(img_bytes, format='PNG')
img_bytes.seek(0)
# Calculate the width and height of the QR code image
img_width = 60 # Fixed width for the QR code
img_height = img.size[1] * (img_width / img.size[0])
# Calculate the position to center the QR code
x = (pdf.w - img_width) / 2
y = (pdf.h - img_height) / 2 - 10
pdf.image(img_bytes, x=x, y=y, w=img_width, h=img_height)
# Write the title in parentheses below the QR code
pdf.set_font("Arial", size=12)
pdf.set_y(y + img_height + 10) # Adjust the y-position to place the text below the QR code
pdf.cell(0, 10, text=f"({title})", align='C')
pdf.add_page() # Blank page
def sentences_to_pdf(pdf, sentences):
for sentence in sentences:
img = create_qr_code(sentence)
img_bytes = BytesIO()
img.save(img_bytes, format='PNG')
img_bytes.seek(0)
pdf.add_page()
# Calculate the width and height of the QR code image
img_width = pdf.w - 2 * pdf.l_margin
pdf_image = pdf.image(img_bytes, x=pdf.l_margin, y=pdf.t_margin, w=img_width)
# Calculate the height of the QR code image
img_height = (img.size[1] / img.size[0]) * img_width
def split_into_sentences(text):
# Use regular expression to split by dot followed by a space or end of string
sentences = re.split(r'(?<=\.)\s*', text)
# Remove empty strings from the list of sentences
sentences = [sentence for sentence in sentences if sentence]
return sentences
def main(title, sentences):
# Create an instance of FPDF
pdf = FPDF(format=((110, 110)))
pdf.set_auto_page_break(auto=True, margin=15)
# Add a title page
title_page(pdf, title)
# Add sentences to the PDF
sentences_to_pdf(pdf, sentences)
# Check the total number of pages
total_pages = pdf.page_no()
# If the total number of pages is odd, add an empty page
if total_pages % 2 != 0:
pdf.add_page()
# Save the PDF to a file
pdf.output("pdfs/qr.pdf")
with open('data/slow_tech.txt', 'r') as f:
txt = f.readlines()
txt = txt[0]
sentences = split_into_sentences(txt)
main('Slow Tech Manifesto', sentences)
/tmp/ipykernel_34470/2275173069.py:40: DeprecationWarning: Substituting font arial by core font helvetica - This is deprecated since v2.7.8, and will soon be removed
pdf.set_font("Arial", size=12)