PDFKit – invalid byte sequence in US-ASCII

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

  1. 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 #

  2. 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’)
    kit.to_file(‘/home/ankit/Desktop/3235.pdf’)

      1. 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’……

      2. 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

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s