rails 3 + prawn pdf + html_safe

我正在使用prawn gem生成PDF报告,

@user.description returns as string "sample text &nspb; 

sample text

"

同时将值附加到pdf表

 pdftable = Prawn::Document.new pdftable.table([["#{@user.description}"]], :column_widths => {0 => 50, 1 => 60, 2 => 280, }, :row_colors => ["ffffff"]) 

在这种情况下生成的pdf具有带有html标签的内容,即使我尝试应用html_safe但它不是转义标签。

是否有可能在prawn pdftable中使用/ apply html_safe,以逃避html标签?

再一次, html_safe不是你应该使用的方法; 它没有做你认为它做的事情。 所有html_safe都将字符串标记为安全,因此告诉Rails它不需要在视图中转义它。 使用Prawn时没有任何效果。

你想要做的不是转义 HTML,而是从字符串中删除 HTML标签。 Rails在ActionView::Helpers::SanitizeHelper有一个HTML ActionView::Helpers::SanitizeHelper ,但默认情况下它允许某些标记; 您可以使用tags属性关闭此行为。

 class MyClass include ActionView::Helpers::SanitizeHelper def remove_html(string) sanitize(string, :tags => {}) # empty tags hash tells it to allow no tags end end obj = MyClass.new obj.remove_html "sample text &nspb; 

sample text

" => "sample text &nspb; sample text"

您可以在控制器中include ActionView::Helpers::SanitizeHelper以访问sanitize方法。

请注意,   仍然在字符串中; 如果要删除这些HTML实体,则需要使用其他方法; HTMLEntities gem就是这样一种方法:

 [1] pry(main)> require 'htmlentities' => true [2] pry(main)> coder = HTMLEntities.new => # [3] pry(main)> string = "sample text   sample text" => "sample text   sample text" [4] pry(main)> coder.decode string => "sample text  sample text" 

(请注意,在您的示例中,文本显示为&nspb;而不是  )。

如果您正在寻找一种使用虾的内联格式的方法,您可以执行以下操作:

 pdftable = Prawn::Document.new cell = make_cell(content: "#{@user.description}", inline_format: true) pdftable.table([[cell]])