-
I tried using the legacy For example: tw = fitz.TextWriter(...)
print(fitz.get_text_length("我爱PyMuPDF!", fontsize=36, fontname="Helv"))
tw.append(fitz.Point(0, 100), "我爱PyMuPDF!", fontsize=36)
print(tw.text_rect.width) This gives 194.03999948501587 and 295.2773742675781, presumably b/c the first one would render as My workaround is to instead construct a temporary Anyone see a better way? And should the docs of |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment
-
The correct (and fastest) way would be to use the PyMuPDF class 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.29200160503387
font2.text_length("我爱PyMuPDF!",fontsize=36)
257.2920016050339
font2.text_length("我爱PyMuPDF!",fontsize=36)-font2.text_length("PyMuPDF!",fontsize=36)
72.0
# if using text writer, use insertion END POINT to compare:
tw=fitz.TextWriter(fitz.paper_rect("a4"))
tw.append((0,0),"我爱PyMuPDF!",fontsize=36,font=font)
(Rect(-36.891998291015625, -66.1240234375, 274.1679992675781, 38.76397705078125), Point(246.02398681640625, 0.0))
# end point is Point(246.02398681640625, 0.0) The TW rectangle includes a few reserves, which makes the use of its width dubious. You can be even shorter and create/distroy the font.char_lengths("我爱PyMuPDF!",fontsize=36)
(36.0, 36.0, 24.01199984550476, 18.0, 29.98800015449524, 20.015999794006348, 24.01199984550476, 25.992000102996826, 21.996000051498413, 10.007999897003174) |
Beta Was this translation helpful? Give feedback.
The correct (and fastest) way would be to use the PyMuPDF class
Font
. No need to employ TextWriter: