我有一个 Controller Action ,可以呈现 pdf 供下载。 我想将多个 pdf 渲染到一个 tmp 文件夹(然后将它们压缩以供下载)
我可以生成 pdf 并呈现给用户,但我不知道如何创建一个文件夹来存储它们。
我用的是 Prawn 。它有 render_file
方法将它保存到文件系统,但我不知道它是什么目录,或者其他用户是否可以将他们的 pdf 保存到同一个文件夹,所以我需要为创建一个 uniques 文件夹每个用户然后将 pdf 保存在那里。
我该怎么做?
目前我的 Controller Action 是
def showpdf
respond_to do |format|
format.html
format.pdf do
@items.each do |pdf|
pdf = Prawn::Document.new(page_size: "A4",margin: [0,0,0,0])
# pdf creation stuff...
# this was used previously to render one pdf to the browser
# but I need to save multiple pdf's
#send_data pdf.render, filename: 'report.pdf', type: 'application/pdf'
end
end
end
最佳答案
你需要将所有文件存储到 tmp/your-folder 文件夹中,像这样
require 'prawn'
@items.each do |item|
pdf = Prawn::Document.new
pdf.text("Lets Zip All.")
pdf.render_file('tmp/your-folder/#{item.id}.pdf')
end
然后简单地使用https://github.com/rubyzip/rubyzip压缩你的文件夹。
require 'zip'
folder = "tmp/your-folder/"
zipfile_name = "tmp/archive.zip"
input_filenames = Dir.entries("tmp/your-folder/").select {|f| !File.directory? f}
Zip::File.open(zipfile_name, Zip::File::CREATE) do |zipfile|
input_filenames.each do |filename|
zipfile.add(filename, folder + '/' + filename)
end
zipfile.get_output_stream("myFile") { |os| os.write "myFile contains just this" }
end
只需将文件发送给用户。但是,如果 PDF 包含大量数据,则将它们移至延迟作业。 希望这是有道理的,但如果没有,请点击回复。
关于ruby-on-rails - Rails 将多个 pdf 文件渲染到一个文件夹,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35044632/