2013-02-16 18 views
0

我正在使用PDFKit將部分視圖呈現爲PDF文件。但是,在嘗試使用render_to_string(首選方法)時遇到了一些問題,而不是外部Web請求。PDFKit with Rails使用render_to_string創建格式錯誤的文本

使用URL時,渲染PDF文件:

html = render_to_string :partial => "agreement" 
pdf = PDFKit.new(html , page_size: 'Letter').to_pdf 
*from the console* 
html => "\n\n<style>\n #contract h2{text-align: center; margin-bottom: 10px;}\n #contract em{font-weight: bold; text-decoration: underline; font-style: normal;}\n #contract p.tab{margin-left: 25px;}\n #contract ol{list-style:lower-alpha;}\n #contract ol li{margin-left: 25px; font-size: 1em; line-height: 1.615em; color: #555; margin-bottom: 5px;}\n #contract b{font-weight: bold;}\n #contract p p{margin-left: 10px;}\n</style>\n<div id=\"contract\">\n <p>This agreement (「<b>Agreement</b>」) is entered into... 

Malformatted Text

html = "#{root_url}/contracts/#{@contract.id}" 
pdf = PDFKit.new(html, page_size: 'Letter').to_pdf 

Proper Text

PDF文件使用render_to_string渲染時

我在做什麼錯?

+0

您可能試圖在具有ASCII編碼的頁面中顯示unicode符號(引號)。這個問題與'pdf'沒有任何關係,在你的html頭部添加''。 – mudasobwa 2013-02-16 09:09:35

+0

我試過了,這似乎並沒有訣竅。在這兩種情況下,PDFKit都提供了相同的html,但只有一個具有較差的編碼。 – 2013-02-16 09:20:03

回答

3

您在源部分中有彎曲的引號。控制檯輸出顯示如下:

...<p>This agreement (「<b>Agreement</b>」)... 

彎曲的引號是UTF-8字符,但PDFKit默認將它們解析爲ASCII。見this question


EDIT:在直接渲染串傳遞需要使用UTF-8編碼的字符串。 Ruby 1.9默認會這樣做。在Ruby 1.8中,請嘗試以下操作:

html = render_to_string :partial => "agreement", :encoding => "UTF-8" 
+0

我試着在編輯中添加上面的編碼,並將「html.toutf8()」直接傳入PDFKit。兩者似乎都不起作用: -/ – 2013-02-16 16:52:36

+0

我向您提供的鏈接中建議的html標題添加了確實有用。謝謝! – 2013-02-16 16:55:21

+0

將元標記添加到上面的註釋中,對我來說工作得非常好:) – 2015-02-23 12:10:08