【问题标题】:PDFKit with Rails creates malformatted text using render_to_string带有 Rails 的 PDFKit 使用 render_to_string 创建格式错误的文本
【发布时间】:2013-02-01 05:58:59
【问题描述】:

我正在使用 PDFKit 将部分视图呈现为 PDF 文件。但是,我在尝试使用 render_to_string(首选方法)而不是外部 Web 请求时遇到了一些问题。

使用 url 呈现时的 pdf 文件:

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

使用 render_to_string 渲染时的 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...

我做错了什么?

【问题讨论】:

  • 您可能试图在具有ASCII 编码的页面中显示 unicode 符号(引号)。问题与pdf无关,在你html的head中添加&lt;meta encoding="utf-8"&gt;
  • 我试过了,但这似乎没有奏效。在这两种情况下,为 PDFKit 提供了相同的 html,但只有一种编码较差。

标签: ruby-on-rails ruby encoding pdfkit


【解决方案1】:

您在源部分中有弯引号。控制台输出显示:

...<p>This agreement (“<b>Agreement</b>”)...

弯引号是 UTF-8 字符,但 PDFKit 默认将它们解析为 ASCII。见this question


编辑:传入直接呈现的字符串要求字符串使用 UTF-8 编码。 Ruby 1.9 默认执行此操作。在 Ruby 1.8 中,尝试以下操作:

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

【讨论】:

  • 我已经尝试添加上面的编码,如您的编辑所示,以及将“html.toutf8()”直接传递到 PDFKit。两者似乎都不起作用:-/
  • 我按照您提供的链接中的建议将 添加到 html 标头中,并且它确实有效。谢谢!
  • 从上面的评论中将元标记添加到 中,对我来说也非常好:)
猜你喜欢
  • 2017-03-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-05
  • 1970-01-01
  • 2015-11-21
  • 2020-12-16
  • 1970-01-01
相关资源
最近更新 更多