【问题标题】:How to print generated PDF automatically with Wicked PDF?如何使用 Wicked PDF 自动打印生成的 PDF?
【发布时间】:2017-01-11 08:03:26
【问题描述】:

我正在使用 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

【问题讨论】:

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


    【解决方案1】:

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

    【讨论】:

    • 在 Ubuntu 中运行良好,谢谢。
    【解决方案2】:

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

    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,而不是在新选项卡中打开。

    【讨论】:

    • @Mohamad Yakout 这个解决方案对我不起作用。这两种生成 PDF 格式有什么区别?
    • 您的服务器是 WEBrick 服务器,您使用 rails s 运行 .. 当您发送请求时您的服务器停止了?您是否面临这个问题?
    • @Mohamad Yakout 我在五号轨道上,所以我有 Puma 而不是 WEBrick。不,我的服务器不会停止!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-23
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多