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

This method inserts text into a predefined rectangular area of a (new or existing) PDF page. Words are distributed across the available space, put on new lines when required etc. Line breaks and tab characters are respected / resolved. Text can be aligned in the box (left, center, right) and fonts can be freely chosen. The method returns a float indicating how vertical space is left over after filling the area.

Python, 15 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
import fitz                           # import PyMuPDF
doc = fitz.open("some.pdf")           # or new: fitz.open(), followed by insertPage()
page = doc[n]                         # choose some page
rect = fitz.Rect(50, 100, 300, 400)   # rectangle (left, top, right, bottom) in pixels

text = """This text will only appear in the rectangle. Depending on width, new lines are generated as required.\n<- This forced line break will also appear.\tNow a very long word: abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ.\nIt will be broken into pieces."""

rc = page.insertTextbox(rect, text, fontsize = 12, # choose fontsize (float)
                   fontname = "Times-Roman",       # a PDF standard font
                   fontfile = None,                # could be a file on your system
                   align = 0)                      # 0 = left, 1 = center, 2 = right

print("unused rectangle height: %g" % rc)          # just demo (should display "44.2")

doc.saveIncr()   # update file. Save to new instead by doc.save("new.pdf",...)

Choosing the right font is quite flexible:

  1. fontname = "xxxxx", fontfile = None - xxxxx must be one of the 14 PDF standard fonts
  2. fontname = "xxxxx", fontfile = ".../??????.ttf" - embed and use some new fontfile
  3. fontname = "/xxxxx", fontfile = None - xxxxx must reference a font already used by the page.

Only this new text is put on the page - background is transparent. If anything is already there, it will "shine through". To prevent this, first fill the rectangle with some color using the drawRect method:

page.drawRect(rect, color = white, fill = white) # white is the tuple (1, 1, 1),

then do insertTextbox.

1 comment

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

Some new features of the insertTextbox() method include justified alignment and the option to rotate the text by multiples of 90 degrees.

For example, insertTextbox(..., rotate = 90, ...) will fill the rectangle bottom up with text that can be read by turning the screen 90 degrees clockwise.

The method will now always return a float and no longer raise an exception for insufficient space. If negative, rc indicates the space deficit to store the text, and no change will have been made.