Ubuntu 18.04.1 LTS下用html-pdf生成PDF遇Fontconfig警告求助
Hey there, let’s dig into that fontconfig warning that’s stopping your PDF generation with html-pdf on Ubuntu 18.04.1 LTS. I’ve dealt with similar issues before, so let’s walk through targeted fixes that might work even after you’ve tried common GitHub solutions.
Root Cause
This warning usually stems from misconfigured system locale settings—PhantomJS (which html-pdf relies on) is pretty sensitive to UTF-8 locale setup, and Ubuntu 18.04 sometimes has incomplete or improperly activated locale configurations.
Step-by-Step Solutions
1. Repair System Locale Configuration
First, check your current locale setup with:
locale
If you see empty values for LC_ALL or non-UTF-8 entries, generate and set the correct locale:
# Generate en_US.UTF-8 locale sudo locale-gen en_US.UTF-8 # Set it as the global default sudo update-locale LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8
Log out and back in, then run locale again to confirm all entries show en_US.UTF-8.
2. Force Locale for Node.js Process
Sometimes system-wide settings don’t propagate to Node.js. Launch your app with explicit locale variables:
LC_ALL=en_US.UTF-8 LANG=en_US.UTF-8 node your-app.js
If using a process manager like PM2, add the variables to your config file:
// ecosystem.config.js module.exports = { apps: [{ name: 'your-project', script: 'app.js', env: { LC_ALL: 'en_US.UTF-8', LANG: 'en_US.UTF-8' } }] };
3. Install Missing System Fonts
PhantomJS needs proper system fonts to render PDFs correctly. Install common free fonts to eliminate font-related fallback issues:
sudo apt-get install -y fonts-wqy-microhei fonts-dejavu-core fonts-freefont-ttf
Restart your Node.js app after installation.
4. Explicitly Set Locale in html-pdf Options
Add locale environment variables directly to your html-pdf configuration to bypass system-level inconsistencies:
const pdf = require('html-pdf'); const pdfOptions = { env: { LC_ALL: 'en_US.UTF-8', LANG: 'en_US.UTF-8' } // Add other options like format, orientation as needed }; pdf.create(yourHtmlContent, pdfOptions).toFile('./output.pdf', (err, result) => { if (err) return console.error('PDF generation failed:', err); console.log('PDF saved:', result.filename); });
5. Switch to a More Reliable PDF Generator (Last Resort)
If PhantomJS continues to give you grief, consider replacing html-pdf with html-pdf-chrome—it uses Chrome Headless instead of PhantomJS, has better modern web support, and is less sensitive to locale quirks.
内容的提问来源于stack exchange,提问作者Prathamesh mhatre

