PDF Writer gem不支持特殊字符

时间:2017-05-11 06:59:53

标签: ruby

为什么pdf作者不支持使用ruby的特殊字符和俄文,中文字母

1 个答案:

答案 0 :(得分:0)

pdf writer不是UTF-8,但您可以像下面这样实施解决方案

覆盖PDF :: Writer文本方法

将以下代码放在lib目录中名为pdfwriter_extensions.rb(或您选择调用它)的文件中:

CONVERTER = Iconv.new( 'ISO-8859-15//IGNORE//TRANSLIT', 'utf-8')

module PDF
    class Writer
        alias_method :old_text, :text

        def text(textto, options = {})
            old_text(CONVERTER.iconv(textto), options)
        end

    end
end

在处理PDF输出的控制器中添加:

require 'pdf/writer'
require 'pdfwriter_extensions'

之后你可以像教程一样使用PDF :: Writer:

pdf = PDF::Writer.new
pdf.select_font "Helvetica", :encoding => nil
pdf.text "User name: <b>#{@user.name}</b>", :font_size => 16, :justification => :left
send_data pdf.render, :disposition => 'inline', :filename => "user_details.pdf", :type => "application/pdf"

N.B:我从https://www.peterkrantz.com/2007/utf8-in-pdf-writer/

采取了这个解决方案