Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using external TTF fonts to generate PDF with Japanese text using prawn

Prawn has a limited number of fonts under Prawn::BASEDIR}/data/fonts/

I have tried gkai00mp.ttf, but generated PDF shows only the 1st letter "千" of 千葉, for example.

I feel like this font is good for Chinese characters.

font("#{Prawn::BASEDIR}/data/fonts/gkai00mp.ttf") do
  text "千葉"
end

Is it possible to upload and use external fonts? If yes, where that fonts can be obtained from?

My environment: Latest Ruby and Rails. Prawn version 0.12.0

like image 805
Askar Avatar asked Dec 09 '13 05:12

Askar


2 Answers

Here I want to share with the solution.

I have also posted the issue here https://github.com/prawnpdf/prawn/issues/595 and the advice was:

The TTF fonts that ship with Prawn are for testing and use with the manual... they're not meant for regular use. Do a web search for "Free Japanese TTF font" and I'm sure you'll probably find something.

So, I have googled and found http://www.wazu.jp/gallery/Fonts_Japanese.html and tested mona.ttf, in particular, and this worked.

like image 89
Askar Avatar answered Nov 15 '22 09:11

Askar


I recently used Prawn (version 2.0.2 with prawn-table version 0.2.2) to generate a PDF in Japanese, and unfortunately didn't have any luck with any of the TTF fonts posted in the accepted answer (the accepted answer was still of great help in knowing that Japanese text can't be rendered with Prawn's built-in fonts, though!).

I did, however, have luck using the TTF files from IPA fonts with Prawn, specifically the "4 fonts package" they have listed on the page which contains the IPA Mincho and IPA Gothic fonts. I used the IPAPMincho font (ipamp.ttf) for "normal" font, and IPAPGothic (ipagp.ttf) for "bold"; they are different fonts, but one worked for me as the "bold version" of the other.

In my Prawn configuration, I used default fonts where I could (say, for English documents), but the TTF files for Japanese, which were configured in on-the-fly. This lead to code that looked similar to the following:

Prawn::Document.generate("MyJapaneseDocument.pdf") do |pdf|
  # assume `font_name` here is something like "IPA",
  # ie not a font that is shipped with the Prawn gem
  unless Prawn::Font::AFM::BUILT_INS.include?(font_name)
    pdf.font_families.update(
      font_name => {
        normal: "path/to/ipamp.ttf",
        bold: "path/to/ipagp.ttf"
      }
    )
  end
  pdf.font font_name
end
like image 40
Paul Fioravanti Avatar answered Nov 15 '22 08:11

Paul Fioravanti