import pymupdf as fitz
def add_attached_text(self, page, text, font, isHeader):
if not text:
return
rect = page.rect
rotation = page.rotation
margin = 20
font_size = 9
font_color = (1, 0, 0) # red
try:
text_width = 0
for c in text.strip():
try:
code = ord(c)
advance = font.glyph_advance(code)
except:
advance = font.glyph_advance(0xfffd)
text_width += advance * font_size
# alignment: right
x = max(rect.x0 + 5, rect.width - text_width - margin)
if isHeader:
y = margin
else:
y = rect.height - margin - font_size
p = fitz.Point(x, y)
print(f"add text corrdinates: {p},transto:{p * page.derotation_matrix}")
if page.rotation == 90:
p = p * page.derotation_matrix
tw = fitz.TextWriter(page.rect, color=font_color)
tw.append(p, text, font=font, fontsize=font_size)
tw.write_text(page)
# page.insert_text(p,
# text,
# fontname="china-ss",
# fontsize=font_size,
# color=font_color,
# rotate=page.rotation,
# render_mode=0)
# page.insert_htmlbox(
# (x-5, y, x+text_width, y+25),
# text,
# css="* {font-family: cjk; font-size:9px; color: red;}", #
# rotate=page.rotation)
except Exception as e:
print("err:", str(e))
def insert_text(self, pdffile, outfile):
doc = fitz.open(pdffile)
page = doc[0]
font = fitz.Font("cjk")
print(f"page-rotation:{page.rotation}")
add_attached_text(self, page, "中文Text123试验test", font, True)
add_attached_text(self, page, "日期2025-3-16", font, False)
doc.save(outfile)
if __name__ == "__main__":
# input_pdf = "test-1-portrait.pdf"
# output_pdf = "test1-out.pdf"
# insert_text(None, input_pdf, output_pdf)
input_pdf = "test-2-landscape.pdf"
output_pdf = "test2-out.pdf"
insert_text(None, input_pdf, output_pdf)`
When the page.rotation is 90 degrees (displayed as landscape orientation), the header/footer text positioning becomes problematic, whereas it works fine when page.rotation is 0 degrees (also landscape orientation by default). The issue manifests as text vertically aligned along the right edge of the page from top to bottom - essentially normal horizontal text rotated 90 degrees clockwise around the right edge as the origin. However, TextWriter's append() and write_text() methods lack a rotate parameter, making it unclear how to correct this orientation.
If using insert_text() with mixed Chinese/English text, English letters and numbers occupy double-width spacing (visually unappealing) and the pre-calculated text width becomes inaccurate, causing truncation. insert_htmlbox() appears to embed fonts regardless of font-family specifications, bloating file sizes from 700KB to over 30MB compared to insert_text().
The goal is to either:
Use insert_text() with fontname="cjk" while maintaining consistent Chinese/English character spacing, OR
Implement TextWriter with proper text positioning that handles page rotation correctly.
attached files:
test1-out.pdf
test-2-landscape.pdf
test2-out.pdf
test-1-portrait.pdf