foxlog
4/11/2018 - 8:22 AM

## Ruby 打印PDF文档,类似python的Reportlab math exam 计算题

Ruby 打印PDF文档,类似python的Reportlab math exam 计算题

## 本地解决中文字体,Table的问题,

# 小学生口算题打印

require 'prawn'
require 'prawn/table'

USER_PATH = File.expand_path("~#{ENV['USER']}")
a = 0
b = 0
c = 0
def _getRuleOne()
a = rand(10..70)
b = rand(10..70)
while a + b>=100
a = rand(10..70)
b = rand(10..70)
end

return "%2d + %2d =" % [a, b]

end

def _getRuleThree()
a = rand(10..70)
b = rand(10..70)
while a - b<=0
a = rand(10..70)
b = rand(10..70)
end

return "%2d - %2d =" % [a, b]

end

def _getRuleTwo()
a = rand(10..70)
b = rand(2..9)
c = rand(3..9)
while a + b*c >=100
a = rand(10..70)
b = rand(2..9)
c = rand(3..9)
end

return "%2d + %1d x %1d =" % [a, b, c]

end

def _getRuleFour()
a = rand(10..70)
b = rand(3..9)
c = rand(2..9)
while a - b*c <=0
a = rand(10..70)
b = rand(3..9)
c = rand(2..9)
end

return "%2d - %1d x %1d =" % [a, b, c]

end

def getAllData()
resultOne = []
resultTwo = []
resultThree = []
resultFour = []
for i in 0..15
resultOne.push(_getRuleOne())
resultTwo.push(_getRuleTwo())
resultThree.push(_getRuleThree())
resultFour.push(_getRuleFour())
end

return resultOne.zip(resultTwo).zip(resultThree).zip(resultFour).flatten.each_slice(4).to_a
end

# Assignment
pdf = Prawn::Document.new :left_margin => 80

#pdf.text "口算测验  姓名          班级          得分          " , :align => :center

# 通过 :inline_format需要font family
pdf.font_families.update("Microsoft YaHei" => {
:normal => USER_PATH + "/Library/Fonts/msyh.ttf",
#:italic => "/Library/Fonts/Arial Italic.ttf",
:bold => USER_PATH + "/Library/Fonts/msyhbd.ttf",
#:bold_italic => "/Library/Fonts/Arial Bold Italic.ttf"
})

pdf.font "Microsoft YaHei"

# HTML方式不支持多个字体设置,需要用formatted_text
#pdf.text "<font size=1> <b>口算测验</b></font>  <font size=16> 姓名         班级          得分</font> " , :inline_format => true, :align => :center

## 在同一行不同的字体设置,使用formatted_text
pdf.formatted_text [{:text => "口算测验", :size => 30, :styles => [:bold]},{text: "   姓名____________班级__________得分_________" , :size => 18}]

pdf.move_down(50)

data = getAllData()
pdf.font_size = 12

pdf.table data,