Skip to content

Text not being inserted after bookmark #111

@s892307

Description

@s892307

Describe the bug

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

require 'docx'

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?

To Reproduce

Use class/file above and run the method against a document with a few bookmarks.

Sample docx file

sample.docx

Expected behavior

Expected all text inserts after bookmarks to work.

Environment

  • Ruby version: [2.7.0]
  • docx gem version: [0.6.1]
  • OS: [macOS Big Sur]

Metadata

Metadata

Assignees

No one assigned

    Labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions