WeasyPrint字体问题导致所有字符被方框替代
Hey there, let's tackle this frustrating font issue with WeasyPrint! Those square boxes mean the tool can't find or embed any fonts, even though you installed it via pip install weasyprint. Let's go through step-by-step fixes:
1. Double-Check System-Level Dependencies
WeasyPrint doesn't just rely on Python packages—it needs system libraries for rendering and font handling. Pip doesn't install these, so they might be missing entirely:
- Debian/Ubuntu: Run this to install required libraries + a basic font pack:
sudo apt-get install libpango-1.0-0 libpangoft2-1.0-0 libcairo2 libgdk-pixbuf2.0-0 fonts-dejavu-core - macOS (Homebrew):
brew install pango cairo gdk-pixbuf - Windows: You'll need the GTK3 runtime (make sure it's added to your system PATH—WeasyPrint relies on this for low-level rendering).
2. Confirm WeasyPrint Can See Your System Fonts
If your OS doesn't have basic fonts installed, WeasyPrint has nothing to embed. Let's check what fonts it can detect:
Run this quick Python snippet:
from weasyprint.fonts import FontConfiguration font_config = FontConfiguration() print("Fonts WeasyPrint can access:", list(font_config.get_font_families()))
If the list is empty or missing common fonts like DejaVu Sans, install a basic font package (like fonts-dejavu-core on Ubuntu) or manually add standard fonts like Arial/Times New Roman.
3. Force Font Usage with Explicit CSS
Complex pages like Wikipedia have conflicting font styles that can confuse WeasyPrint. Add this CSS to force a known, available font:
* { font-family: DejaVu Sans, Arial, sans-serif !important; -weasy-print-color-adjust: exact; }
The !important ensures this font takes priority over page-specific styles, and -weasy-print-color-adjust: exact helps with consistent embedding.
4. Test with a Minimal HTML File
Rule out issues with the target page's complexity by creating a simple test file:
<!DOCTYPE html> <html> <head> <style> body { font-family: DejaVu Sans; } </style> </head> <body> <h1>Test Font Embedding</h1> <p>If this renders correctly, the problem is with your original HTML's styles.</p> </body> </html>
Render it with:
python -m weasyprint test.html test.pdf
Open the PDF, go to its properties (in most viewers: File > Properties > Fonts) and check if DejaVu Sans is listed as embedded.
5. Upgrade WeasyPrint and Dependencies
Older versions have known font embedding bugs. Upgrade to the latest version:
pip install --upgrade weasyprint
Also, update your system libraries (e.g., sudo apt update && sudo apt upgrade on Ubuntu) to ensure full compatibility.
Bonus: Check Verbose Logs for Clues
If none of the above works, run WeasyPrint with verbose output to spot specific errors:
python -m weasyprint --verbose your-input.html output.pdf
Look for lines mentioning "font" or "embedding"—they'll point to missing files or configuration missteps.
内容的提问来源于stack exchange,提问作者Constantin




