Convert HTML to word file ?

让人想犯罪 __ 提交于 2019-11-26 09:55:41

问题


How to convert ruby file in word file i.e (docx file). For pdf, we prawn gem. But is there any gem for word file. I am trying to convert my html file in word file so that it can be editable for user too. What should do in that case ? I was planning to convert that file in word file. Will it be possible or not.


回答1:


If you are using Rails:

in initializers/mime_types.rb:

Mime::Type.register 'application/vnd.ms-word', :msword 

in your controller:

say you want to export show action:

def show
  @item = Item.find params[:id]
  respond_to do |format|
    format.html # show.html.erb
    format.xml { render :xml => @item }
    format.msword { set_header('msword', "#{@item.title}.doc") }
    format.pdf do
        render :pdf => 'Coming soon...', :layout => false
    end
  end
 end

define set_header in application_controller.rb:

def set_header(p_type, filename)
  case p_type
    when 'xls'
     headers['Content-Type'] = "application/vnd.ms-excel; charset=UTF-8'"
     headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
     headers['Cache-Control'] = ''

    when 'msword'
     headers['Content-Type'] = "application/vnd.ms-word; charset=UTF-8"
     headers['Content-Disposition'] = "attachment; filename=\"#{filename}\""
     headers['Cache-Control'] = ''

   end
 end

now define a show.msword.erb #you can use any template handler like haml etc.

YOUR HTML HERE TO EXPORT TO DOC
AS LIKE NORMAL ERB TEMPLATE



回答2:


Use htmltoword gem. https://github.com/nickfrandsen/htmltoword

it hasn't been updated since November 2015, but works well.



来源:https://stackoverflow.com/questions/18372210/convert-html-to-word-file

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!