首页 > 解决方案 > 获取'未定义的方法`view_paths ='#你的意思?在 Rails 中使用 PDFKit 的 view_paths 错误

问题描述

我正在使用 PDFKit(连同 Gem render_anywhere 和 wkhtmltopdf-binary)来创建一个按钮,用于在 Rails 中从 HTML 创建 PDF。我遵循了几个都使用“发票”作为示例的教程。我的应用程序使用“审计”。我以为我已经完成了所有事情,但是在 ActionView::LookupContext object: 上出现错误undefined method 'view_paths=' for #<ActionView::LookupContext:0x00007fdb191d6cc0> Did you mean? view_path。它与错误的路径和在 Rails 中使用服务类有关,但似乎找不到解决方案。这是我制作PDF的代码:

PDFKit 宝石:https ://github.com/pdfkit/pdfkit

我正在使用的教程:https ://code.tutsplus.com/tutorials/generating-pdfs-from-html-with-rails--cms-22918

downloads_controller: _

class DownloadsController < ApplicationController


   def show
    respond_to do |format|
      format.pdf { send_audit_pdf }
    end
  end

  private

  def audit_pdf
    audit = params[:incoming]
    AuditPdf.new(audit)
  end

  def send_audit_pdf
    send_file audit_pdf.to_pdf,
      filename: audit_pdf.filename,
      type: "application/pdf",
      disposition: "inline"
  end

end

Download型号:

require "render_anywhere"

class Download 
  include RenderAnywhere

  def initialize(audit)
    @audit = audit
  end

  def to_pdf
    kit = PDFKit.new(as_html, page_size: 'A4')
    kit.to_file("#{Rails.root}/public/audit.pdf")
  end

  def filename
    "audit #{audit.id}.pdf"
  end

  private

    attr_reader :audit

    def as_html
      render template: "audits/pdf", layout: "audit_pdf", locals: { audit: audit }
    end
end



我的views/layout/audit_pdf.html.erb样子是这样的:

<!DOCTYPE html>
<html>
<head>
  <title>Audit PDF</title>
  <style>
    <%= Rails.application.assets.find_asset('audit.pdf').to_s %>
  </style>
</head>
<body>
  <%= yield %>
</body>
</html>

标签: ruby-on-railsrubywkhtmltopdfpdfkitactionview

解决方案


由于您仅使用 rails api,因此您正面临这个问题。

你需要改变

def as_html
  render template: "audits/pdf", layout: "audit_pdf", locals: { audit: audit }
end

至:

def pdf_html
  ActionController::Base.new.render_to_string(template: 'audits/pdf.html.erb', layout: 'audit_pdf.erb')
end

推荐阅读