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

Version 1.11.0 of PyMuPDF allows creating new PDF pages, as well as inserting images into existing pages.

Here is a script that converts any textfile into a PDF.

Python, 48 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
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
from __future__ import print_function
import fitz
import sys
assert len(sys.argv) == 2,"usage: python %s text.file" % (sys.argv[0],)
ifn = sys.argv[1]
ofn = ifn + ".pdf"           # name of PDF output
#------------------------------------------------------------------------------
# A very basic text-to-PDF converter.
#------------------------------------------------------------------------------
width = 595                  # these are DIN-A4
height = 842                 # portrait values
fontsz = 10                  # font size
font = "Courier"             # choose a Base 14 font here
lineheight = fontsz * 1.2    # line height is 20% larger than fontsize

# this yields the following lines per page:
nlines = int((height - 108.0) / lineheight + 0.5) - 1

sourcefile = open(ifn)       # we are going to convert this file
line_ctr = 0
total_ctr = 0
out_buf = ""

doc = fitz.open()            # new empty PDF

def page_out(b):
    doc.insertPage(-1, fontsize = fontsz, text = b, fontname = font,
                   width = width, height = height)
    
while 1:
    line = sourcefile.readline()
    if line == "": break
    out_buf += line
    line_ctr += 1
    total_ctr += 1
    if line_ctr == nlines:
        page_out(out_buf)
        out_buf = ""
        line_ctr = 0

if len(out_buf) > 0:
    page_out(out_buf)

print("Statistics for PDF conversion of", ifn)
print(total_ctr, "lines read / written,", nlines, "lines per page.")
print(ofn, "contains", len(doc), "pages.")
doc.save(ofn, garbage=4, deflate=True)
doc.close()