Integrate htmltoword with Rails
masterFor htmltoword version >= 0.2, an action controller renderer is provided. You can respond to the .docx format directly. The gem will look for views with the .docx.erb extension.
Using View Templates
Create a view file named my_view.docx.erb. This file contains the HTML structure that will be converted into the Word document.
Example my_view.docx.erb:
<h1 class="custom-title"> My custom template </h1>
<%= render partial: 'my_partial', collection: @objects, as: :item %>Controller Implementation
You can use respond_with or the render docx: syntax.
Using respond_with:
def my_action
respond_with(@object, filename: 'my_file.docx', word_template: 'my_template.docx')
endUsing render docx::
def my_action2
respond_to do |format|
format.docx do
render docx: 'my_view', filename: 'my_file.docx'
end
end
endDirect HTML Content:
If you don't want to use a .docx.erb template, you can pass the HTML string directly via the content key:
render docx: 'my_file.docx', content: '<html><body><h1>Hello</h1></body></html>'def my_action
respond_to :docx
# ...
respond_with(@object, filename: 'my_file.docx', word_template: 'my_template.docx')
end