您的位置:首页 > 大数据 > 人工智能

rails实现PDF文档导出功能

2018-01-10 20:20 459 查看
业务系统中,经常有导出PDF的需求,现使用
prawn
来实现这一功能。

gem install prawn
;

bundle exec rake manual
生成manual.pdf帮助文档;

将自己需要的字体拷贝至
"#{Prawn::DATADIR}/fonts/"
路径下;

目前的需求很简单,只需要将文字内容转化成pdf:

def generate_pdf(content)
Prawn::Document.generate("test.pdf") do
file = "#{Prawn::DATADIR}/fonts/gkai00mp.ttf"
font_families["Kai"] = {
:normal => { :file => file, :font => "Kai" }
}
text content, :fallback_fonts => ["Times-Roman", "Kai"]
end
end


现在想实现这样的一个功能:将
markdown
编写个人简历导出成
pdf
格式。然而
prawn
无法转化
html
格式,因此放弃使用,选择
pdfkit


Gemfile
中添加
gem 'pdfkit'
gem 'wkhtmltopdf-binary'
,然后执行
bundle install


定义路由:

get 'download', to: 'welcome#download_resume'


代码实现:

# app/controllers/welcome_controller.rb

def download_resume
resume = current_user.resume
content = resume.content_html.nil? ? resume.content : resume.content_html
kit = PDFKit.new(content, page_size: 'Letter')
pdf = kit.to_pdf
file_name = "#{current_user.username}的个人简历.pdf"
send_data(pdf, filename: file_name)
end
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐