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

问题描述 投票:5回答:3

我有一个小的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。我知道我需要使用TTF字体,但我怎么做呢?我需要在线安装吗?如果是这样,我将把它保存到哪里?我知道这可能是一个愚蠢的问题,但我是Ruby和Prawn的新手。谢谢!

ruby pdf prawn
3个回答
7
投票

ttf是一种常见格式,你可以在Google font下载字体,例如,将字体放在项目的某个目录中,例如/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

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


0
投票

如果您使用普通的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

0
投票

防止此错误的快速而肮脏的解决方法是在将文本写入pdf文件之前将文本编码为windows-1252。

text = text.encode("Windows-1252", invalid: :replace, undef: :replace, replace: '')

这种方法的一个缺点是,如果您要转换的字符在Windows-1252编码中无效或未定义,它将被替换为空字符串''根据您的原始文本,此解决方案可能正常工作,或者您可能最终缺少PDF中的几个字符。

© www.soinside.com 2019 - 2024. All rights reserved.