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