Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby - How to use different fonts in Prawn?

Tags:

ruby

pdf

prawn

I have a small Ruby program where I'm printing some text out to a PDF using Prawn, but a small portion of the text is non-English characters. (Some of that text is Chinese, some is Greek, etc.). When I run my program, I of course get an error saying Your document includes text that's not compatible with the Windows-1252 character set. (Prawn::Errors::IncompatibleStringEncoding) If you need full UTF-8 support, use TTF fonts instead of PDF's built-in fonts. I know that I need to use a TTF font, but how do I even go about that? Do I need to install it from online? If so, where would I save it to? I know that's probably a dumb question but I'm new to Ruby and Prawn. Thanks!

like image 245
Reign Avatar asked May 17 '16 22:05

Reign


2 Answers

ttf is a common format, you can download fonts at Google font for instance, put the font in some directory in your project for instance under /assets/fonts/

You can then define a new font family like so:

Prawn::Document.generate("output.pdf") do
  font_families.update("Arial" => {
    :normal => "/assets/fonts/Arial.ttf",
    :italic => "/assets/fonts/Arial Italic.ttf",
  })
  font "Arial"
end

You can then use the font throughout your document.

like image 191
Jan Bussieck Avatar answered Sep 27 '22 18:09

Jan Bussieck


A quick and dirty work-around to prevent this error is to encode your text to windows-1252 before writing it to the pdf file.

text = text.encode("Windows-1252", invalid: :replace, undef: :replace, replace: '')

A drawback to this approach is that, if the character you are converting is invalid or undefined in Windows-1252 encoding, it will be replaced by an empty string '' Depending on your original text, this solution may work fine, or you may end up missing a few characters in your PDF.

like image 39
Hula_Zell Avatar answered Sep 27 '22 17:09

Hula_Zell