从.doc,.docx和rtf文件中抓取文本并将其显示到文本字段(Rails)

时间:2012-10-21 02:09:52

标签: ruby-on-rails forms doc

我有Post型号:

  create_table "posts", :force => true do |t|
    t.string   "title"
    t.string   "content"
    t.integer  "user_id"
    t.datetime "created_at",                            :null => false
    t.datetime "updated_at",                            :null => false
    t.integer  "comments_count",     :default => 0,     :null => false
    t.boolean  "published",          :default => false
    t.datetime "published_at"
    t.boolean  "draft",              :default => false
  end

这就是它的形式:

<%= form_for(@post, :html => { :multipart => true }) do |f| %>
  <%= render 'shared/error_messages' %>
  <div class="field">
    <%= f.label :title %>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :content %>
    <%= f.text_area :content %>
  </div>

  <div class="field">
    <%= f.label :draft %>
    <%= f.check_box :draft %>
  </div>
  <div class="actions">
    <%= f.submit %>
  </div>
<% end %>

我正在寻找一种从.doc, .docx, and rtf文件中获取文本并将其显示在content文本字段中的方法(这样用户无需打开文件,复制和粘贴将文字转化为形式)。

有什么建议吗?

(是否有任何宝石,文本编辑器或jQuery插件可以实现这一目标?)?

修改

卡在这里:

post.rb:

class Post < ActiveRecord::Base
  require 'docx'
  .
  .
  .  
  def read_docx
    d = Docx::Document.open(self.document)
    d.each_paragraph do |p|
      puts d
    end
  end
end

posts_controller.rb:

class PostsController < ApplicationController
  before_filter :authenticate_user!, :except => [:show, :index]
  .
  .
  .
  def create
    @user = current_user
    @post = @user.posts.new(params[:post])
    @doc_text = (no idea what to do here)

    if @post.save
      redirect_to @post, notice: 'post was successfully created.'
    else
      render action: "new"
    end
  end

  def edit
    @post = Post.find(params[:id])
  end
  .
  .
  .

帖/ new.html.erb:

<%= form_for(@post, :html => { :multipart => true }) do |f| %>
  <%= render 'shared/error_messages' %>
  <div class="field">
    <%= f.label :title %>
    <%= f.text_field :title %>
  </div>
  <div class="field">
    <%= f.label :content %>
    <%= f.text_area :content, :value => @doc_text %>
  </div>
  .
  .
  .

我已经制作了Paperclip上传docx文件

我创建了一个名为:document

的新字段

1 个答案:

答案 0 :(得分:3)

我只是尝试了docx gem,它运行正常。您可以在其github页面上获得2个示例。可悲的是,它不适用于doc文件。

对于他们,你可以使用这个宝石here。在github页面上有一些例子,但是如果你想获得doc文件的全部内容,就这样做:

require 'msworddoc-extractor'

MSWordDoc::Extractor.load('sample.doc') do |doc|
  puts doc.whole_contents
end

您可以为doc调用其他方法,例如documentheader。再次,检查github页面。

对于rtf,您也可以使用此gem

现在,将它传递到content内部很容易。只是定义如何从文件中获取数据,如控制器上调用的外部库:

@doc_text = Parser.doc("file.doc")
@docx_text = Parser.docx("file.docx")
@rtf_text = Parser.rtf("file.rtf")

或者直接或通过您想到的任何方法获取值。要在视图中显示它,您只需添加:value选项,如下所示:

<%= f.text_area :content, :value => @doc_text %> 
#Where @doc_text is the data from file