下载的文档名称中出现不需要的字符



我正在使用WickedPDF gem生成PDF,但我面临的问题是,创建的文档的文档名称为Document20200309-48764-1o1nyyu.PDF,但文档名称应为document.PDF。我不确定为什么要在document之后使用字符。请帮我解决这个问题。

pdf_file = WickedPdf.new.pdf_from_string(
render_to_string(template: 'documents/document.pdf.erb',  locals: { payments: @payments }),
formats: :html,
encoding: "utf8",
)
if pdf_file.present?
tempfile = Tempfile.new(["Document", '.pdf'], Rails.root.join('tmp'))
tempfile.binmode
tempfile.write pdf_file
tempfile.close     
tempfile.unlink
end

更新

path = "Documents"
dir = File.dirname(path)
unless File.directory?(dir)
FileUtils.mkdir_p(dir)
end
path << ".pdf"
file = File.new(path, 'w')
file.write pdf_file
@money.money_receipt = File.open(path)
@money.save
file.close
file.unlink

Tempfile使用第一个参数作为生成文件名的前缀。它添加了额外的字符以确保文件名的唯一性。

如果您想要一个特定的文件名,请考虑使用常规的文件编写器方法。不过,您有责任在之后取消链接该文件,除非Tempfiles,当Tempfile对象被垃圾收集时,Tempfiles将被取消链接。

您创建了一个文档id为path = "Documents-#{@document.id}"的路径。

然后在路径变量的末尾添加.pdf,然后使用它生成一个文件名

path << ".pdf"
file = File.new(path, 'w')

如果你写file = File.new("Document.pdf"),它会生成正确的名称

最新更新