Andres Pérez
Andres Pérez

Reputation: 49

RUBY plain text to Docx with specific formatting

I regularly have to produce word documents that are pretty standard. The content changes regarding certain parameters, but it's always a mix of pre-written stuff. So I decided to write some ruby code to do this more easily and it works pretty well on creating the txt file with the final text I need.

The problem is that I need this text converted to .docx and with specific formatting. So, I'm trying to find a way to indicate in the text file which text should be bold, italic, have different indentation, or be a footnote, to make it easy to interpret (like html does). For example:

<b>this text should be bold</b>
\t indentation works with the tabs
<i>hopefully this could be italic</i>
<f>and I wish this could be a footnote of the previous phrase</f>

However, I haven't been able to do this.

Does anybody know how this can be achieved? I've read about macros and pandoc, but haven't had any luck achieving this. Seems too complicated for macros. Maybe what I'm trying is not the best way. Perhaps with LaTeX or creating html and then converting to word? Can html create footnotes? (that seems to be the most complicated)

I have no idea, I just learned Ruby with a video tutorial, so my knowledge is very limited.

Thanks everybody!

EDIT: Arjun's answer solved almost the whole issue, but the gem he pointed out doesn't include a funcionality for footnotes, which unfortunately constitute a big part of my documents. So if anybody knows a gem that does, would be greatly appreciated. Thanks!

Upvotes: 2

Views: 1771

Answers (1)

arjun
arjun

Reputation: 1614

Ahh Ruby got gems for that ;)
https://github.com/trade-informatics/caracal

This would help you to write docs from Ruby code itself.

From the Readme

docx.p 'this text should be bold' do
  style          'custom_style'    # sets the paragraph style. generally used at the exclusion of other attributes.
  align          :left             # sets the alignment. accepts :left, :center, :right, and :both.
  color          '333333'          # sets the font color.
  size           32                # sets the font size. units in 1/2 points.
  bold           true              # sets whether or not to render the text with a bold weight.
  italic         false             # sets whether or not render the text in italic style.
  underline      false             # sets whether or not to underline the text.
  bgcolor        'cccccc'          # sets the background color.
  vertical_align 'superscript'     # sets the vertical alignment.
end

There is also this gem, https://github.com/nickfrandsen/htmltoword, which converts plain html to doc files. I haven't tried it though.

Upvotes: 3

Related Questions