senny / sablon

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

Image not being replaced #142

Closed arvanasse closed 5 years ago

arvanasse commented 5 years ago

I've tried every conceivable way that I can find to add an image to a Word document with sablon with no luck. I've imitated each of the examples from the test but the only result has been that the merge fields are removed (no leftover artifacts).

The template where the images are to be inserted is pretty straightforward:

Screen Shot 2019-11-04 at 9 25 47 PM

The following is the latest attempt to add the sablon content for the image into the context (h):

def build_context
  ...
  filename = "client-logo-#{sow.id}.png"
  destination = Rails.root.join('tmp', filename)
  Down.download(sow.client.logo_url, destination: destination)
  h[:client_logo] = Sablon.content(:image, destination, properties: { height: '1cm', width: '4cm' })
  ...
end

And the use is rather boring:

with_merge_template(sow_template) do |template_path|
  template = Sablon.template(template_path)
  template.render_to_file(output_path, build_context)
end

I can tell that something is happening because the resulting docx is ~22k larger with the client_logo element as compared to when is omitted. Unfortunately, nothing is visible in the document. What am I missing?

arvanasse commented 5 years ago

@stadelmanma I may have stumbled upon the answer but I'm not sure it's satisfactory. As I was grasping at straws looking for differences, I tried to copy/paste whatever object is in the images_template.docx between the start/end blocks. I had assumed that it was a broken image link -- renders as a grey block with a question mark. In Word, I noticed that it allows me to provide image formatting (e.g., how text flows around the image).

If that block is a requirement, eh, it's not great but okay. The unsatisfactory part is that I don't know what it is. I need to communicate it to my teammates and saying, "copy and paste that grey block thing with a question mark in it" doesn't really cut it. Ideally I can tell them how to reproduce it natively within Word. So... what is it?

stadelmanma commented 5 years ago

It is possible depending on your version of MS Word a different set of XML code is being used to render the image. The XML used to display images is nontrivial and we don't inject the entire block, instead only trying to change the relevant pieces.

If you want you can attach of a small relevant excerpt from a troublesome template here and I'll look at it when I have time. (Which admittedly has been in very short supply for the last year).