Ruby - 如何在 Prawn 中使用不同的字体?
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
实际案列:
## bundle exec rails runner ContactEnsureAttachment.prawn_test -e production def self.prawn_test template_filename = "#{Rails.root}/public/ensure_file.pdf" prawn_filename = "#{Rails.root}/public/temp.pdf" output_filename = "#{Rails.root}/public/output.pdf" Prawn::Document.generate(prawn_filename) do start_new_page ## 增加新一页 fill_color 'ff0000' stroke_color 'ff0000' # fill_polygon [50, 150], [150, 200], [250, 150], [250, 50], [150, 0], [50, 50] # # Stroke with Purple using CMYK # stroke_color 50, 100, 0, 0 # stroke_rectangle [300, 300], 200, 100 # # Both together stroke_circle [738, 340], 25 stroke_circle [738, 165], 25 # bounding_box([100, 300], width: 300, height: 200) do # stroke_bounds # stroke_circle [0, 0], 10 # end # font_families.update( # "STFANGSO" => { # :normal => "app/assets/fonts/STFANGSO.TTF" # } # ) # font "STFANGSO" font Rails.root.join("app/assets/fonts/simhei.ttf") # 鈴木 ensure_debit_person = "鈴木鈴鈴木" ensure_credit_person = "木" ensure_debit_person_all = "鈴木 鈴" ensure_credit_person_all = "鈴 木木" pp ensure_debit_person_all.length pp "ddddd" text_debit_preson_opts = ContactEnsureAttachment.get_sign_opts(ensure_debit_person.length, "debit") text_credit_preson_opts = ContactEnsureAttachment.get_sign_opts(ensure_credit_person.length, "credit") # draw_text "藤 一", :at => [734,360], kerning: true, rotate: 270#, align: :center # 358 text_box "#{ensure_debit_person}", text_debit_preson_opts#at: [719, 349], width: 18, size: 18#, overflow: :shrink_to_fit, min_font_size: 10#, align: :center, valign: :center#, style: [:bold, :italic] # draw_text "kai", :at => [734,185], kerning: true, rotate: 270#, align: :center # 174 text_box "#{ensure_credit_person}", text_credit_preson_opts#at: [719, 174], width: 18, size: 18#, align: :center, valign: :center#, style: [:bold, :italic] fill_color '000000' text_box "#{ensure_debit_person_all}", at: [450, 349], size: 14, width:14*ensure_debit_person_all.length text_box "#{ensure_credit_person_all}", at: [450, 167], size: 14, width: 14*ensure_credit_person_all.length text_box "#{ensure_debit_person_all}", at: [450, 390], size: 12, width: 12*ensure_debit_person_all.length end company_logo = CombinePDF.load("#{Rails.root}/public/temp.pdf").pages[1] pdf = CombinePDF.load "#{Rails.root}/public/aaaa.pdf" # pdf.pages.each { |page| page << company_logo } pdf.pages[0] << company_logo pdf.save "#{Rails.root}/public/aaaa.pdf" end
参考链接:
https://www.coder.work/article/1082841