美文网首页
ruby on rails 中使用pdfkit生成pdf

ruby on rails 中使用pdfkit生成pdf

作者: limx | 来源:发表于2016-08-07 21:33 被阅读0次

    说是使用pdfkit,其实做工作的还是wkhtmltopdf。

    一、新建项目

    rails new mypdf --skip-bundle

    进入项目:cd mypdf,打开Gemfile:vim Gemfile

    修改source为https://ruby.taobao.com

    添加:gem 'pdfkit'

    运行bundle install

    二、配置

    在项目目录下的config/initializers里加上pdfkit.rb文件,修改内容为:

    PDFKit.configure do |config|

    config.wkhtmltopdf = '/path/wkhtmltopdf'

    end

    config.wkhtmltopdf配置的是wkhtmltopdf的路径,要确保pdfkit能找到它。

    其它的配置请参考:http://wkhtmltopdf.org/usage/wkhtmltopdf.txt,里面的横杠用下划线代替。

    三、使用

    在controller里的相应位置加入:

    用渲染的模版内容生pdf:

    html = render_to_string(:template => "pdf_template.erb",:layout => false)

    kit = PDFKit.new(html)

    kit.stylesheets << "#{Rails.root}/app/assets/assets/stylesheets/pdf.css"

    #kit.to_pdf # inline PDF

    #kit.to_file('/path/pdf.pdf')

    send_data(kit.to_pdf, :filename => "mypdf.pdf", :type => "application/pdf")

    #render :text => kit.to_pdf

    用url的内容生成pdf:

    url = "http://www.baidu.com"

    kit = PDFKit.new(url)

    # kit.stylesheets << "#{Rails.root}/app/assets/assets/stylesheets/pdf.css" # 用url时就不可以用css样式了。

    #kit.to_pdf # inline PDF

    #kit.to_file('/path/pdf.pdf')

    send_data(kit.to_pdf, :filename => "mypdf.pdf", :type => "application/pdf")

    注: kit = PDFKit.new(url, cookie: {"cookie_name"=>"cookie_content"}),如果需要登录的话,可以用cookie。cookie可以自己获取。

    另外,如果你的页面里有js需要运行,最好在设置文件里设置如下:

    javascript_delay: 1000

    它的默认值是200毫秒。把加大一些,以便让js运行完成。

    这样就可以用了。

    相关文章

      网友评论

          本文标题:ruby on rails 中使用pdfkit生成pdf

          本文链接:https://www.haomeiwen.com/subject/zprlsttx.html