Can't use my own custom font #2289
-
Describe the bugHi, I'm trying to add three text boxes to a file with different custom fonts, but every approach results in a fixed font which is not my custom font. I know it may be duplicated but I searched it in issues and docs but don't know how should I pass my fonts. To ReproduceDownload the 📦 Source Code# pip install pymupdf
import fitz
# Load the PDF file
pdf_file = "Sample.pdf"
doc = fitz.open(pdf_file)
# Load the custom font
font_file1 = r"ZahraRoosta.ttf"
font_file2 = r"CascadiaCode-Regular.ttf"
custom_font = fitz.Font(
fontname="ZahraRoosta",
fontfile=font_file1
)
# Loop through each page of the PDF
for page in doc:
# Get the page dimensions
page_width = page.rect.width
page_height = page.rect.height
# Create a text box with different font settings
text1 = "Sample Text One"
text1_box = fitz.Rect(70, 150, page_width-50, page_height-50)
#page.insert_font(font_file)
page.insert_textbox(text1_box, text1, fontsize=16, fontfile=font_file1, color=(0, 0, 0))
text2 = "متنی دیگر"
text2_box = fitz.Rect(70, 200, page_width-50, page_height-50)
page.insert_textbox(text2_box, text2, fontsize=16, fontfile=font_file1, color=(0, 0, 0))
text2 = "Another Sample Text"
text2_box = fitz.Rect(70, 300, page_width-50, page_height-50)
page.insert_textbox(text2_box, text2, fontsize=16, fontfile=font_file2, color=(0, 0, 0))
# Save the modified PDF file
doc.save("NewOutput.pdf") Expected behaviorDisplay the right section of the image instead of the left. Your configuration
|
Beta Was this translation helpful? Give feedback.
Replies: 4 comments 12 replies
-
Beta Was this translation helpful? Give feedback.
-
This is now being resolved! |
Beta Was this translation helpful? Give feedback.
-
Dear @JorjMcKie I have tried to use your code where two diff fonts are in use F0 and F1, but text with F1 does not appear in pdf. |
Beta Was this translation helpful? Give feedback.
-
@dalius415 - your question cannot be answered like this, as you did not provide any data to reproduce it. You neither mention your operating system or the PyMuPDF version. |
Beta Was this translation helpful? Give feedback.
Your use of
page.insert_textbox()
is incorrect - see corrected version below.Please also note, that this set of text insertions (insert_text / insert_textbox) doen't support writing right-to-left. You must either "emulate" this in your code by reverting such strings, or use
TextWriter
output, which has a right-to-left feature.Other than that, text comes out correctly: