如何使用Wicked PDF自动打印生成的PDF?

时间:2017-01-11 08:03:26

标签: ruby-on-rails ruby wicked-pdf

我正在使用 Wicked PDF,我在单击按钮的同时在新标签中生成pdf。但是我想通过单击按钮来打印pdf。我添加 print_media_type 并设置值 true ,我希望我的打印机选项为开始工作但没有任何反应!有什么想法吗?

respond_to do |format|
        format.html
        format.pdf do
          render pdf: "file_name", :template => 'officials/individual_receipt_export.html.erb', encoding: 'utf8',page_size: 'A4',:print_media_type => true
        end
end

2 个答案:

答案 0 :(得分:5)

实际上, print_media_type 选项用于样式化pdf文件,而不是用于打印它。
要将pdf文件直接发送到打印机,您可以尝试以下操作:

  1. 生成pdf并将其保存到文件中:

    # create a pdf
    pdf = render_to_string pdf: "some_file_name", template: "templates/pdf", encoding: "UTF-8"
    
    # then save to a file
    save_path = Rails.root.join('pdfs','filename.pdf')
    File.open(save_path, 'wb') do |file|
      file << pdf
    end
    
  2. 调用 lpr 命令打印已保存的pdf文件

    system("lpr", "pdfs/filename.pdf")
    

答案 1 :(得分:0)

在您的控制器中尝试以下操作:

def generate_pdf
  render pdf: 'sample_offer_letter', handlers: [:erb], formats: [:html]
end

在“视图”文件夹中,创建文件generate_pdf.html.erb,如下所示:

<!doctype html>
<html>
  <head>
    <meta charset="utf-8">
    <title>PDF Title</title>
    <%= wicked_pdf_stylesheet_link_tag "file.css" -%>
  </head>
  <body>
  <div>    
    <div>
      <%= wicked_pdf_image_tag @image %>
      <div>
        <h4><%= Date.today.strftime("%d %b, %Y") %></h4>
      </div>
    </div>
    <div>
      <div>
        <h3><%= @variable_in_controller %></h3>
      </div>
      <br>
      <strong><%= @content %></strong>
    </div>
  </div>
  </body>
</html>

单击按钮时调用此操作。那与我合作。 此操作允许您在PC中下载PDF,而不是在新选项卡中打开。

相关问题