I’m using PDFKit at VersionEye to generate the PDF invoices. It’s a really awesome project. The idea behind PDFKit is that you generate the documents as HTML and CSS and then convert it to PDF. That works really well. Generating a PDF works like this:
kit = PDFKit.new(html, :footer_html => footer_file, :page_size => 'A4')
The first parameter “html” is the HTML as string. In addition to that you can give a separate path to a HTML file as footer. And of course you can choose the output format. In this case DIN A4.
That worked all really well, but sometimes I got a
invalid byte sequence in US-ASCII Exception
I found out that there was some kind of special character in the HTML. That can happen if you fill the HTML template with usernames for example, and one of the users is a French dude or even worst a Chinese dude, then you have some odd characters in your markup 🙂 But luckily there is a solution for that. You can enforce UTF-8 encoding for the string.
This line fixed it for me.
html = html.force_encoding(Encoding::UTF_8)
7 thoughts on “PDFKit – invalid byte sequence in US-ASCII”
It did not work for me. I have similar senerio with French dude’s username.
but your solution …force_encoding.. did not work for me.
Here is the error:
undefined method `force_encoding’ for #
It looks like you are calling the method “force_encoding” on a String with the value “#”.
Thanks for the reply. but I am calling “force_encoding” on a html.
here is the code:
html_file = File.new(‘/home/ankit/Desktop/3235.html’)
html_file = html_file.force_encoding(Encoding::UTF_8)
kit = PDFKit.new(html_file, :page_size => ‘Letter’)
Which version of Ruby are you running?
ruby 1.9.2 but i have also tried to run the same using ruby version 2.1.5.
It displays the same error as with other versions.
undefined method `force_encoding’……
I only found this here on GitHub: https://github.com/inossidabile/wash_out/issues/1. But it’s related to Ruby 1.8.X.
This did not to help either. Thanks for your responses Robert anyways. I have posted the piece of code which I am using. If you find something please post it here. I shall be Googling more about this.
Thanks and Regards