如何在Python FPDF中实现行内文本加粗并输出非ASCII字符?
Great questions! Let's break this down step by step since FPDF works a bit differently than console output or markdown-style formatting.
Inline Bold Text in FPDF
FPDF doesn’t support inline formatting tags or console escape sequences (that’s why \033 shows up as plain text in your PDF). Instead, you have to manually switch between regular and bold font styles while writing your text. Here’s how to do it:
- Define your fonts: For built-in fonts like Helvetica, FPDF already includes bold variants—you just need to specify the style when switching.
- Switch styles mid-line: Use
ln=Falseincell()to keep the cursor on the same line, so you can toggle between regular and bold text seamlessly.
Example code:
from fpdf import FPDF pdf = FPDF() pdf.add_page() # Start with regular Helvetica pdf.set_font("Helvetica", size=12) pdf.cell(0, 10, txt="This is regular text, ", ln=False) # Switch to bold Helvetica pdf.set_font("Helvetica", style='B', size=12) pdf.cell(0, 10, txt="this part is bold, ", ln=False) # Switch back to regular to finish the line pdf.set_font("Helvetica", size=12) pdf.cell(0, 10, txt="and this is regular again.", ln=True) pdf.output("bold_text_example.pdf")
Supporting Non-ASCII Characters
The original FPDF library has limited Unicode support, so I recommend using fpdf2—the updated, actively maintained fork of FPDF that handles non-ASCII characters (like Chinese, Japanese, accented Latin characters) much better. Here are two common approaches:
Option 1: Use a built-in Unicode font
fpdf2 includes Unicode-friendly fonts like DejaVuSans by default. You can load it and set the encoding to UTF-8:
from fpdf import FPDF pdf = FPDF() pdf.add_page() # Load DejaVuSans (supports most Unicode characters) pdf.add_font("DejaVuSans", "", "DejaVuSans.ttf", uni=True) pdf.set_font("DejaVuSans", size=12) # Now you can output non-ASCII text pdf.cell(0, 10, txt="Hello 世界! こんにちは! ¡Hola!", ln=True) pdf.output("unicode_example.pdf")
Note: If DejaVuSans isn’t on your system, fpdf2 will automatically download it when you run the code, or you can place the font file in your project directory.
Option 2: Use a custom local font
If you need a specific font (like SimSun for Chinese, or Arial Unicode MS), load it using add_font() with the uni=True flag:
from fpdf import FPDF pdf = FPDF() pdf.add_page() # Load a custom Chinese font (replace with your font file path) pdf.add_font("SimSun", "", "SimSun.ttf", uni=True) pdf.set_font("SimSun", size=12) pdf.cell(0, 10, txt="这是一段中文文本。", ln=True) pdf.output("chinese_text_example.pdf")
Just make sure the font file is in your project folder, or provide the full file path to it.
Wrap-up: FPDF relies on font switching for inline formatting, and fpdf2 is the way to go for smooth non-ASCII text support. Both workflows are straightforward once you get the hang of them!
内容的提问来源于stack exchange,提问作者TTT2




