Googling for information on how to use PDF::Writer shows that there are many european developers frustrated with the lack of UTF-8 support in PDF::Writer. As Ruby on Rails works great with UTF-8 these days this can be a bit of an issue.

Part of the problem lies in the fact that the PDF specification (at least up to 1.6) does not support UTF-8 (you can use UTF-16 if you like). I had the misfortune of plowing thorugh it a couple of years ago when developing a PDF form filler library for a customer (don’t ask).

In Ruby on Rails, this is easy to solve as long as you only use Latin characters with diacritics. The solution is to switch encoding back to ISO-8859-15 for text strings you feed to PDF::Writer.

A simple extension to the String class will do the trick:

[ruby] class String require ‘iconv’ def to_iso c = Iconv.new(‘ISO-8859-15’,‘UTF-8’) c.iconv(self) end end [/ruby]

If you are working in Rails you can put this code in the lib folder (I usually call the file string_extensions.rb).

Then, when you call the text method on your PDF::Writer intance you can easily pass a correctly encoded string.

Overriding PDF::Writer text method

A much cleaner approach, as Aníbal describes in the comment below, is to override PDF::Writer’s text method.

Put the following code in a file called pdfwriter_extensions.rb (or whatever you choose to call it) in your lib directory:

[ruby] CONVERTER = Iconv.new( ‘ISO-8859-15//IGNORE//TRANSLIT’, ‘utf-8’)

module PDF class Writer alias_method :old_text, :text

def text(textto, options = {}) old_text(CONVERTER.iconv(textto), options) end

end end [/ruby]

In your controller that handles the PDF output you add:

[ruby] require ‘pdf/writer’ require ‘pdfwriter_extensions’ [/ruby]

…after which you can use PDF::Writer like in the tutorial:

[ruby] pdf = PDF::Writer.new pdf.select_font “Helvetica”, :encoding => nil pdf.text “User name: #{@user.name}”, :font_size => 16, :justification => :left send_data pdf.render, :disposition => ‘inline’, :filename => “user_details.pdf”, :type => “application/pdf” [/ruby]