Welcome, guest | Sign In | My Account | Store | Cart

PyMuPDF (fitz) provides easy to use ways to create PDF documents out of simple texts.

An example is the text output of Python's calendar module. Here we take a starting year as script parameter and output a 3-page (A4 landscape) document with calendars for this and the following two years - in less than 20 lines of code.

Python, 24 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import fitz
import calendar
import sys
assert len(sys.argv) == 2, "need start year as the one and only parameter"

startyear = sys.argv[1]
assert startyear.isdigit(), "year must be positive numeric"
startyear = int(startyear)
assert startyear > 0, "year must be positive numeric"
    
doc = fitz.open()
cal = calendar.LocaleTextCalendar(locale = "de")   # choose your locale
w, h = fitz.PaperSize("a4-l")                      # get sizes for A4 landscape paper

txt = cal.formatyear(startyear, m = 4)
doc.insertPage(-1, txt, fontsize = 12, fontname = "Courier", width = w, height = h)

txt = cal.formatyear(startyear + 1, m = 4)
doc.insertPage(-1, txt, fontsize = 12, fontname = "Courier", width = w, height = h)

txt = cal.formatyear(startyear + 2, m = 4)
doc.insertPage(-1, txt, fontsize = 12, fontname = "Courier", width = w, height = h)

doc.save("Kalender.pdf", garbage = 4, deflate = True)

1 comment

Jorj X. McKie (author) 4 years, 4 months ago  # | flag

Have a look at PyMuPDF's home page https://github.com/rk700/PyMuPDF to see how a different mono-spaced font can be used. There are lots nicer than PDF's "Courier" ...

The only prerequisite is that you have the fontfile available on your system.