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

View this thread on steempeak.com
· @linjiahung · (edited)
[Rails]如何使用wicked pdf生成pdf
![](https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Pdf_by_mimooh.svg/544px-Pdf_by_mimooh.svg.png)

在先前的專案中有產生pdf檔的需求。這邊紀錄一下使用[wicked_pdf](https://github.com/mileszs/wicked_pdf)這個gem產生pdf的一些做法。

如果你僅需要產生簡單的表格的pdf檔,建議可以使用Prawn這個gem,更多用法可以參考railscast([#153 PDFs with Prawn (revised)](https://www.youtube.com/watch?v=e-A3zBeWDdE&t=203s))

## 安裝
首先先安裝`wicked_pdf`
```ruby=
gem 'wicked_pdf'
```

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

```ruby=
gem 'wkhtmltopdf-binary'
```

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

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

## 設定Controller
安裝完後設定controller
```ruby=
class ThingsController < 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](https://github.com/mileszs/wicked_pdf#advanced-usage-with-all-available-options)
## 設定View
設定完controller後讓我們來設定view

```ruby=
<!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 <%= user.first_name %></p>  
</body>
```
產生的檔案如下
![](https://i.imgur.com/2kfB3r7.png)


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

此外記得設定assetpipline,避免deploy的時候出錯
```ruby
config.assets.precompile += ['pdf.css', 'number_pages.js']
```

## 解決中文編碼問題
```html
<meta charset=utf-8" />
```

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

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

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

```
sudo apt-get install fonts-wqy-zenhei
```

參考資料:
- [Wicked PDF](https://github.com/mileszs/wicked_pdf#advanced-usage-with-all-available-options)
- [chinese language does not appear in pdf](https://www.google.com.tw/search?q=wicked+pdf+chinese&rlz=1C5CHFA_enJP558JP558&oq=wicked+pdf+chinese&aqs=chrome..69i57j0.4455j0j9&sourceid=chrome&ie=UTF-8)
- [Install wkhtmltopdf on Ubuntu](https://gist.github.com/brunogaspar/bd89079245923c04be6b0f92af431c10)
👍  
properties (23)
post_id47,218,314
authorlinjiahung
permlinkrails-wicked-pdf-pdf
categorycn
json_metadata"{"links": ["https://github.com/mileszs/wicked_pdf", "https://www.youtube.com/watch?v=e-A3zBeWDdE&t=203s", "https://github.com/mileszs/wicked_pdf#advanced-usage-with-all-available-options", "https://www.google.com.tw/search?q=wicked+pdf+chinese&rlz=1C5CHFA_enJP558JP558&oq=wicked+pdf+chinese&aqs=chrome..69i57j0.4455j0j9&sourceid=chrome&ie=UTF-8", "https://gist.github.com/brunogaspar/bd89079245923c04be6b0f92af431c10"], "format": "markdown", "app": "steemit/0.1", "image": ["https://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Pdf_by_mimooh.svg/544px-Pdf_by_mimooh.svg.png"], "tags": ["cn", "cn-reader", "rails", "pdf", "ubuntu"]}"
created2018-05-06 12:43:15
last_update2018-05-06 12:48:30
depth0
children1
net_rshares4,330,912,608
last_payout2018-05-13 12:43:15
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length2,598
author_reputation52,749,970,637
root_title"[Rails]如何使用wicked pdf生成pdf"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000
author_curate_reward""
vote details (1)
@cn-cutie.pie ·
@linjiahung, 写得好好哇~~~ ![img](https://i.imgur.com/Q9v1T1e.png)
properties (22)
post_id47,218,430
authorcn-cutie.pie
permlink20180506t124406627z-post
categorycn
json_metadata"{"tags": ["cn"]}"
created2018-05-06 12:44:06
last_update2018-05-06 12:44:06
depth1
children0
net_rshares0
last_payout2018-05-13 12:44:06
cashout_time1969-12-31 23:59:59
total_payout_value0.000 SBD
curator_payout_value0.000 SBD
pending_payout_value0.000 SBD
promoted0.000 SBD
body_length61
author_reputation717,060,097,040
root_title"[Rails]如何使用wicked pdf生成pdf"
beneficiaries[]
max_accepted_payout1,000,000.000 SBD
percent_steem_dollars10,000