2015-07-21 38 views
0

我想保存一個我創建的docx。我使用寶石htmltoword。渲染是我認爲的寶石中的一個功能。保存與特定路徑的docx渲染

在我的控制器(但不工作):

respond_to do |format| 
    format.html 
    format.docx do 
    @filepath = "#{Rails.root}/app/template/#{@cvmodif.nom}.docx" 
    render docx: 'show', filename: 'show.docx' 
    send_file(@filepath, :type => 'application/docx', :disposition => 'attachment') 
    end 
end 

我有一個鏈接。當我點擊它時,docx被正確地下載。但我想將它保存在自定義路徑中。

<%= link_to 'WORD', cv_path(@cvmodif, :format => 'docx') %> 

我該怎麼做?

回答

2

rendersend_file都做同樣的事情:生成一個文件並將其作爲附件發送。

如果你想發送前手動你需要做的是將文檔保存:

respond_to do |format| 
    format.docx do 
    # Generate the document 
    my_html = '<html><head></head><body><p>Hello</p></body></html>' 
    file_path = "test-#{Time.now.sec}.docx" 
    document = Htmltoword::Document.create(my_html) 

    # Save it in the custom file 
    File.open(file_path, "wb") do |out| 
     out << document 
    end 

    # Send the custom file 
    send_file(file_path, :type => 'application/docx', :disposition => 'attachment') 
    end 
end 

附:根據0.4.4版本中的Htmltodoc源代碼,有一個函數create_and_save,但在當前分佈的gem中,此函數缺失。如果這種情況經常用在你的應用程序中,我建議你爲此創建一個通用方法。

UPDATE 那麼有沒有簡單的解決方案,因爲在這種情況下發送的文件是繪製過程是頁面的加載的最後一步,深入內部運行的Htmltoword的一部分。

最正確的解決方案是將其作爲Htmltoword的功能。 (創建功能請求或者甚至自己實現)。

但是現在您可以從庫中獲取* .docx文件的渲染器並添加最少的更改以實現您的目標。

創建文件RailsApp/config/initializers/application_controller.rb。 添加的docx渲染這段代碼如果這個文件比較源一個,你會發現,我已經加入save_to選項,當此選項設置從github

ActionController::Renderers.add :docx do |filename, options| 
    formats[0] = :docx unless formats.include?(:docx) || Rails.version < '3.2' 

    # This is ugly and should be solved with regular file utils 
    if options[:template] == action_name 
    if filename =~ %r{^([^\/]+)/(.+)$} 
     options[:prefixes] ||= [] 
     options[:prefixes].unshift $1 
     options[:template] = $2 
    else 
     options[:template] = filename 
    end 
    end 

    # disposition/filename 
    disposition = options.delete(:disposition) || 'attachment' 
    if file_name = options.delete(:filename) 
    file_name += '.docx' unless file_name =~ /\.docx$/ 
    else 
    file_name = "#{filename.gsub(/^.*\//, '')}.docx" 
    end 

    # other properties 
    save_to = options.delete(:save_to) 
    word_template = options.delete(:word_template) || nil 
    extras = options.delete(:extras) || false 

    # content will come from property content unless not specified 
    # then it will look for a template. 
    content = options.delete(:content) || render_to_string(options) 
    document = Htmltoword::Document.create(content, word_template, extras) 
    File.open(save_to, "wb") { |out| out << document } if save_to 
    send_data document, filename: file_name, type: Mime::DOCX, disposition: disposition 
end 

採取渲染器保存文檔到給定的位置。

使用控制器:

format.docx do 
    render docx: 'my_view', filename: 'my_file.docx', save_to: "test-#{Time.now.sec}.docx" 
end 
+0

好了,但我沒有任何原始的HTML。我有一個'show.docx.erb'我把我的html裏面 –

+0

看看更新的答案。 –

+1

感謝您的幫助,但這不起作用。我沒有錯誤,但沒有創建文件。也許是因爲我在窗戶上。我已經在0.4.4 –