【问题标题】:PDFKit usage Rails 5PDFKit 使用 Rails 5
【发布时间】:2018-06-18 09:17:18
【问题描述】:

我已成功在 Windows 10 上安装 PDFKit 和 wkhtmltopdf 以与 Rails 5 一起使用。

但我找不到任何有关如何将html.erb 文件呈现为 PDF 的相关示例。

我看了一下:pdfkit Usage,它可以将任何网站保存为 PDF。

我有一个<div>,我想将其呈现为 PDF。

【问题讨论】:

    标签: html ruby-on-rails ruby pdfkit


    【解决方案1】:

    我建议您使用Wicked_pdf gem 在 Rails 上生成快速简单的 pdf。 Herewicked pdfpdfkit 的一些示例。

    【讨论】:

    • @maxpuissant 如果您愿意,我还可以通过 Wicked_pdf 帮助您提供一些源代码。
    • 嗨,感谢您的回答@ATF,我在我的控制器中试过这个:kit = PDFKit.new(File.new('app/views/daoes/edit.html.erb')) kit.to_file(Rails.root + 'demo.pdf') 我的终端出现以下错误:Error: Failed loading page file:///mnt/c/Users/Harri/Documents/argia/app/views/daoes/edit.html.erb (sometimes it will work just to ignore this error with --load-error-handling ignore) Exit with code 1, due to unknown error.
    • 这样更好,在终端我通过Printing pages (6/6)看到完整的处理但是生成的PDF是空的。
    • @MaxPuissant 你安装了这个 gem 吗? gem 'wkhtmltopdf-binary', '~> 0.12.3' 这可能是一个原因。让我知道它是否有效!
    【解决方案2】:

    答案:

    1) 添加gem 'pdfkit gem 'wkhtmltopdf-binary' 给 Gemfile。

    2) 运行bundle install

    3) 安装wkhtmltopdf,运行which wkhtmltopdf,然后将此路径粘贴到config/initializers/pdfkit.rb

    `# config/initializers/pdfkit.rb
         PDFKit.configure do |config|
          config.wkhtmltopdf = '/home/harri/.rbenv/shims/wkhtmltopdf'
          config.default_options = {
            :page_size => 'A4',
            :encoding      => 'UTF-8',
            :print_media_type => true
          }
          config.default_options[:load_error_handling] = 'ignore'
    

    # 仅当您的外部主机名在服务器上不可用时使用。 config.root_url = "http://localhost" config.verbose = false 结束`

    4) 在您的控制器中:

    `html = render_to_string(:action => "edit", :layout => false)
          kit = PDFKit.new(html)
          kit.stylesheets << "#{Rails.root}/app/assets/stylesheets/pdf.css"
          #kit.to_file("#{Rails.root}/public/system/daoe/daoe" + @daoe.id.to_s+'.pdf')
    send_data(kit.to_pdf, :filename => 'report.pdf', :type => 'application/pdf', :disposition => 'inline'`        
    

    如果要保存 PDF,请使用 kit.to_file,如果要呈现 PDF 整页,请使用 send_data。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-06-03
      • 2017-05-03
      • 1970-01-01
      • 2016-12-01
      • 1970-01-01
      • 2011-06-08
      相关资源
      最近更新 更多