Prawn: Print unicode string in PDF

2019-07-23 17:27发布

问题:

I'm using Prawn to generate PDFs in a Rails 3 app.

Is it possible to print a Unicode string into a PDF like in a HTML view?

For example,

<%= raw "unicode_for_&#x0F40;" %>

in show.html.erb results in the glyph ཀ while

pdf.text raw "unicode_for_&#x0F40;"

in show.pdf.prawn results in the string "unicode_for_&#x0F40;"

Tried in show.pdf.prawn:

    pdf.font "#{Prawn::BASEDIR}/data/fonts/TibMachUni-1.901b.ttf" do
      pdf.text raw "unicode_for_&#x0F40;"
    end

and

    pdf.font_families.update("TibMachUni" => {:normal => "#{Prawn::BASEDIR}/data/fonts/TibMachUni-1.901b.ttf" })
    pdf.font("TibMachUni") do 
      pdf.text raw "unicode_for_&#x0F40;"
    end

This did not solve the problem.

回答1:

You should use

pdf.text raw "unicode_for_\u0F40"

instead of

pdf.text raw "unicode_for_&#x0F40;"

The Ruby way to escape unicode characters is \uXXXX.

The &#x0F40; escape is an HTML/XML escape code and works only because the first view generated an HTML file.