You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用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:

Solution 1: Embed an emoji-friendly font in your stylesheet

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.

  1. Grab the font file: Download Noto Color Emoji (the TTF format works best) and place it in your Rails project’s app/assets/fonts directory.
  2. 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.

Solution 2: Point wkhtmltopdf to your system’s emoji 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.

Solution 3: Double-check your HTML charset setup

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.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 17:40:16