我有一个 Sinatra 应用程序,它需要以 Microsoft Word 格式提供可下载的报告。我创建报告的方法是使用 ERB 生成内容,然后将生成的 HTML 转换为 docx。 Pandoc似乎是完成此任务的最佳工具,但我的实现涉及生成一些感觉很笨拙的临时文件。
有没有更直接的方法来生成 docx 文件并将其发送给用户?
我知道PandocRuby存在,但我不能完全让它为我的目的工作。这是我当前实现的示例:
#setting up the docx mime type
configure do
mime_type :docx, 'application/vnd.openxmlformats-officedocument.wordprocessingml.document'
end
# route to generate the report
get '/report/:name' do
content_type :docx
input = erb :report, :layout=>false #get the HTML content for the input file
now = Time.now.to_i.to_s #create a unique file name
input_path = File.join('tmp', now+'.txt')
f = File.new(input_path, "w+")
f.write(input.to_s) #write HTML to the input to the file
f.close()
output_path = File.join('tmp', now+'.docx') # create a unique output file
system "pandoc -f html -t docx -o #{output_path} #{input_path}" # convert the input file to docs
send_file output_path
end