如何在Rails的服务器中保存生成的pdf

问题描述:

当前,我正在使用Rails的对虾宝石生成pdf.当用户点击此操作时会生成pdf

Currently I am generating a pdf using prawn gem of rails. pdf is generated when user hit on this action

def print_pdf
    @user = User.find(params[:id])
    @details = @user.details_data
    respond_to do |format|
      format.pdf do
        pdf = PrintDetailsPdf.new(@user, view_context, @details)

          send_data pdf.render, filename: "#{@user.id}.pdf",
                  type: 'application/pdf',
                  disposition: 'inline'
      end
    end
  end

在上述操作中,我生成了pdf并将其显示在浏览器中,并且效果很好.但我想在浏览器中显示pdf,并将pdf保存在服务器的public/user_details目录中.我怎样才能做到这一点?

In above action, I generate the pdf and show it in browser and it works perfectly. But I want to show the pdf in browser and also save the pdf at server in public/user_details directory. How can I do that?

有一些出色的宝石可以帮助文件上传和保存. 此处是这些宝石的列表.回形针和载波是最受欢迎的选择.

There are some good gems that help in file uploading and saving. Here is a list of these gems. Paperclip and Carrierwave are the most popular options.

您也可以从头开始实施它. Rails具有内置的帮助程序,可以轻松推出自己的解决方案.

You could also implement it from scratch. Rails has built-in helpers which make it easy to roll your own solution.

pdf_content = *Content you want to save in the file*
File.open(Rails.root.join('public', 'user_details', filename), 'wb') do |file|
  file.write(pdf_content.read)
end

这取决于您要实现的目标的复杂性,但这对于完成简单的文件保存任务来说已经足够了.在此处中查找更多信息.

It depends on the complexity of what you want to achieve, but this is totally sufficient for easy file saving tasks. Go here to find more information.