I am using prawn gem to generate PDF reports,
@user.description returns as string "<b>sample text</b> &nspb; <p>sample text</p>"
while appending values to the pdf table
pdftable = Prawn::Document.new
pdftable.table([["#{@user.description}"]],
:column_widths => {0 => 50, 1 => 60, 2 => 280, }, :row_colors => ["ffffff"])
in this case generated pdf has content with html tags, even i tried applying html_safe but it is not escaping tags.
is it possible to use/apply html_safe inside prawn pdftable, in order to escape html tags?
Once again, html_safe
is not the method you should be using; it doesn't do what you think it does. All html_safe
does is mark the string as safe, thus telling Rails that it does not need to escape it in a view. When using Prawn it would have no effect.
What it sounds like you want to do is not escape HTML, but strip HTML tags from the string. Rails has an HTML sanitizer in ActionView::Helpers::SanitizeHelper
, but by default it allows certain tags; you can turn this behavior off using the tags
attribute.
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 "<b>sample text</b> &nspb; <p>sample text</p>"
=> "sample text &nspb; sample text"
You can include ActionView::Helpers::SanitizeHelper
in your controller to get access to the sanitize
method.
Note that the
is still in the string; if you want to remove these HTML entities, you'll need to use some other method; the HTMLEntities gem is one such method:
[1] pry(main)> require 'htmlentities'
=> true
[2] pry(main)> coder = HTMLEntities.new
=> #<HTMLEntities:0x007fb1c126a910 @flavor="xhtml1">
[3] pry(main)> string = "sample text sample text"
=> "sample text sample text"
[4] pry(main)> coder.decode string
=> "sample text sample text"
(note that in your example, the text says &nspb;
instead of
).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With