Ruby - How to use different fonts in Prawn?

2020-07-10 07:21发布

问题:

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!

回答1:

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.



回答2:

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.



回答3:

If you are using plain Ruby you could try this way:

require 'prawn'

Prawn::Document.generate("my_text.pdf") do

  font('Helvetica', size: 50) do
    formatted_text_box(
      [{text: 'Whatever text you need to print'}],
      at: [0, bounds.top],
      width: 100,
      height: 50,
      overflow: :shrink_to_fit,
      disable_wrap_by_char: true  # <---- newly added in 1.2
    )
  end
end


标签: ruby pdf prawn