Ruby – 如何在Prawn中使用不同的字体?

我有一个小的Ruby程序,我使用Prawn将一些文本打印成PDF,但文本的一小部分是非英文字符。 (其中一些是中文,一些是希腊文等)。 当我运行我的程序时,我当然会收到一条错误消息,说明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 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 。 我知道我需要使用TTF字体,但我怎么做呢? 我需要在线安装吗? 如果是这样,我将把它保存到哪里? 我知道这可能是一个愚蠢的问题,但我是Ruby和Prawn的新手。 谢谢!

ttf是一种常见的格式,你可以用Google字体下载字体,例如,将字体放在项目的某个目录中,例如/assets/fonts/

然后,您可以定义一个新的字体系列,如下所示:

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

然后,您可以在整个文档中使用该字体。

如果您使用纯Ruby您可以尝试这种方式:

 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