[Rails]如何使用wicked pdf生成pdf

JiaHung Lin
4 min readMay 7, 2018

--

在先前的專案中有產生pdf檔的需求。這邊紀錄一下使用wicked_pdf這個gem的一些做法。

如果你僅需要產生簡單的表格的pdf檔,建議可以使用Prawn這個gem,更多用法可以參考railscast([#153 PDFs with Prawn (revised)]

安裝

首先先安裝wicked_pdf

gem 'wicked_pdf'

除了wicked_pdf這個gem之外,你還必須另外安裝wkhtmltopdf-binary這個gem,因為實際上wicked_pdf是使用wkhtmltopdf這個command line tools來把html轉成pdf。

gem 'wkhtmltopdf-binary'

在你的production server上也記得要安裝,如果你的server的database使用ubuntu的話,指令如下

sudo apt-get update
sudo apt-get install xvfb libfontconfig wkhtmltopdf

設定Controller

安裝完後設定controller

class UsersController < ApplicationController
def show
user = User.find(params[:id])
respond_to do |format|
format.html
format.pdf do
render pdf: “file_name”, # Excluding “.pdf” extension.
show_as_html: params.key?(‘debug’),
locals: {:user => user}
end
end
end
end

這邊我們使用了幾個比較常見的選項

1. pdf:這個選項可以設定輸出的檔名
2. show_as_html:使用這個選項,然後在url加上debug作為query string(如:localhost:3000/users/1?debug),就可以把pdf檔轉回成html。這個選項多是用做debug之用。
3. locals:傳變數進入view

想了解更多選項可以參考:Advanced Usage with all available options

設定View

設定完controller後讓我們來設定view

<!DOCTYPE html>
<html>
<head>
<title>PDF</title>
<meta charset=”utf-8">
<%= wicked_pdf_stylesheet_link_tag “pdf” -%>
<%= wicked_pdf_javascript_include_tag “number_pages” %>
</head>
<body>
<h1>PDF Generation</h1>
<p>I am <%= current_user.first_name %></p>
</body>

產生的畫面如下圖

如果需要引入css和javascript的話,記得使wicked_pdf_stylesheet_link_tag和wicked_pdf_javascript_include_tag來引入。

此外記得設定assetpipline,避免deploy的時候出錯

config.assets.precompile += [‘pdf.css’, ‘number_pages.js’]

解決中文編碼問題

<meta charset=utf-8" />

如果要印出的是中文字,記得要設定語系編碼,否則會出現亂碼。

解決中文字型無法顯示問題

先前在上production的時候,會出現中文字型無法顯示的問題。如果出現這樣的問題多是因為server上沒有中文字型。

發生這樣的問題的話記得安裝字型就可以解決了。

sudo apt-get install fonts-wqy-zenhei

參考資料:
- Wicked PDF
- Chinese language does not appear in pdf
- Install wkhtmltopdf on Ubuntu

--

--