2013-02-16 76 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