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

How to print generated PDF automatically with 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

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

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

然后在 Views 文件夹中,创建文件 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,而不是在新选项卡中打开。

实际上,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")