Skip to content

How do I measure text length with TextWriter? (fitz.get_text_length not recommended) #1915

Answered by JorjMcKie
cbm755 asked this question in Q&A
Discussion options

You must be logged in to vote

The correct (and fastest) way would be to use the PyMuPDF class Font. No need to employ TextWriter:

import fitz
font = fitz.Font("helv")  # supports the same fontcodes as the traditional "insert_text"
# this this the correct number, and also uses the fallback feature:
font.text_length("我爱PyMuPDF!",fontsize=36)  
246.02399969100952
# crosscheck
font.text_length("PyMuPDF!",fontsize=36)
174.02399969100952
# difference:
font.text_length("我爱PyMuPDF!",fontsize=36)-font.text_length("PyMuPDF!",fontsize=36)
72.0
# which is plausible, because Chinese are monospace, 72 = 2 times fontsize

# crosscheck: use Droid Sans Fallback font:
font2=fitz.Font("cjk")
font2.text_length("PyMuPDF!",fontsize=36)
185…

Replies: 1 comment

Comment options

You must be logged in to vote
0 replies
Answer selected by cbm755
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Category
Q&A
Labels
None yet
2 participants