senny / sablon

Ruby Document Template Processor based on docx templates and Mail Merge fields.
MIT License
447 stars 128 forks source link

Controlling styles (e.g font size) of HTML output in template #145

Open pbojinov opened 4 years ago

pbojinov commented 4 years ago

Is it possible to control the style (such as font-size and font-family) of HTML output in the template or does it have to be defined as an inline style? e.g. <p style="font-size: 9px; font-family: Roboto">Hello World</p>

For example, my template is all 7pt Roboto font but the HTML output comes put as 12pt Calibri by default.

From digging into the source code and docs it seems like this might use the custom html/css configuration, I'm just not sure how to configure it for this use-case.

Thank you.

pbojinov commented 4 years ago

I was able to style my HTML by using Nokogiri and a simple function to iterate over the HTML and add the styles, but the issue I'm now facing is Sablon is still applying some styling that I am not able to override.

In this screenshot below, the Activity column still has large bullet points while the Notes column is fine since it is just a div.

image

def formatted_note_html(content)
  if !content.to_s.empty?
    fragment = Nokogiri::HTML.fragment(content.to_s)
    fragment.children.each do |node| 
      styles = 'font-size: 7px; font-family: Roboto;'
      if node.text?
        node.wrap('<div style="#{styles}">')
      else
        node.set_attribute("style", "#{styles}")
      end
    end
    return fragment.to_s
  end
end
pbojinov commented 4 years ago

Another approach I tried with no avail is to modify the List and List Paragraph styles inside of Word

image

stadelmanma commented 4 years ago

Sablon itself applies no specific styling to paragraphs other than setting pStyle=Paragraph for <p> tags and pStyle=Normal for<div> tags unless you have the style="..." attribute set in the HTML code. We also don't modify the actual style definitions defined by Word in any way. All styles applied via the style="..." attribute get attached directly to the XML element in question.

The example in your first comment should work, although I don't think we support the "font-family" property so it will probably get dropped. See test/fixtures/html/html_test_content.html for HTML content examples.

faizaankhan commented 4 years ago

@stadelmanma Can it be done using word ml insertion as per the OpenXML API ?https://docs.microsoft.com/en-us/office/open-xml/how-to-set-the-font-for-a-text-run

stadelmanma commented 4 years ago

@faizaankhan you certainly could inject raw WordML to get the styles you want and depending on your needs you might need to do that since not everything is supported. I would try using HTML insertion first since it's simpler and many options are supported via the style=.... attribute. See https://github.com/senny/sablon/blob/master/lib/sablon/configuration/configuration.rb#L107 for a list of all CSS conversions.