使用wicked_pdf gem在PDF中显示表情符号与特殊字符的问题
Hey there! I’ve dealt with this exact emoji display headache using wicked_pdf before—total bummer when those fun little icons turn into blank boxes. The core issue is that wkhtmltopdf (the tool wicked_pdf relies on under the hood) uses a default font that doesn’t support emoji characters. Let’s fix this with a few straightforward solutions:
This is the most reliable cross-platform fix. We’ll add a font that includes emoji support (like Google’s open-source Noto Color Emoji) and tell our PDF styles to fall back to it when rendering emojis.
- Grab the font file: Download Noto Color Emoji (the TTF format works best) and place it in your Rails project’s
app/assets/fontsdirectory. - Update your PDF stylesheet (
app/assets/stylesheets/pdf.scss):@font-face { font-family: 'NotoColorEmoji'; src: url('NotoColorEmoji.ttf') format('truetype'); font-weight: normal; font-style: normal; } body { // Keep your default font first, then add the emoji font as a fallback font-family: 'Arial', 'NotoColorEmoji', sans-serif; }
This way, regular text uses your default font, and emojis automatically switch to the emoji-friendly font.
If you already have an emoji-supporting font installed on your server/system (like Apple Color Emoji on macOS, or Noto Color Emoji on Linux), you can configure wicked_pdf to tell wkhtmltopdf where to find it.
Add this to your config/initializers/wicked_pdf.rb file:
WickedPdf.config = { # Adjust the exe_path if you're using a custom wkhtmltopdf installation exe_path: '/usr/local/bin/wkhtmltopdf', extra: [ '--font-path', '/usr/share/fonts', # Linux font path # Use '--font-path', '/Library/Fonts' for macOS instead '--enable-local-file-access' ] }
Make sure the --font-path points to the directory where your system stores fonts.
You already have the UTF-8 meta tag, but let’s make it as explicit as possible to avoid any charset mismatches. Update your meta tag in base_pdf.erb to:
meta http-equiv="Content-Type" content="text/html; charset=utf-8"
Combining the content type and charset into one tag can prevent edge-case issues where the charset declaration gets ignored.
Once you’ve implemented one of these solutions, test with your sample emoji text:
🍃 This is 🥯 🍔 🌭 Hot Dog 🥖🍗 Hamburgers🍕
Your emojis should render perfectly in the generated PDF!
内容的提问来源于stack exchange,提问作者Samuel D.

