Ruby docx gem not inserting text into document

Viewed 179

I have the following class to read from a template and create a new docx file:-

require 'docx'

class DocX
  def generate_doc
    # Create a Docx::Document object for our existing docx file
    doc = Docx::Document.open("#{Rails.root}/app/lib/docx_templates/sample.docx")

    doc.bookmarks['cypsldshvlxb'].insert_text_after("Hello, world")

    # Iterate over each table
    doc.tables.each do |table|
      last_row = table.rows.last

      # Copy last row and insert a new one before last row
      new_row = last_row.copy
      new_row.insert_before(last_row)

      # Substitute text in each cell of this new row
      new_row.cells.each do |cell|
        cell.paragraphs.each do |paragraph|
          paragraph.each_text_run do |text|
            text.substitute('_placeholder_', 'replacement value')
          end
        end
      end
    end

    doc.save("#{Rails.root}/app/lib/docx_templates/sample_edited.docx")
  end

end

Most of the above is pulled from the README docs for this gem.

The new file is saved without any errors, but the code which inserts text "Hello, world", has no effect. The text substitution in the table works fine, as well as the new row insertion.

I got the bookmark name by just using the below, so I know it exists, but maybe I'm using the wrong name for it:-

doc.bookmarks.each_pair { |name, object| puts name }

Does anyone know what I could be doing wrong?

0 Answers
Related