1

I've been trying for some days to center an image horizontally inside a .docx file generated from HTML with docx4j without success. What I've tried so far (and works in HTML) is:

<div align="center"><img alt="" src="data:image/png;base64,/9j/4AAQSkZJ..."></div>

(by centering outer div)

<div><img alt="" src="data:image/png;base64,/9j/4AAQSkZJ..." clase="img-default"></div>

with the following commands inside Style tag:

.img-default {
    margin: 0 auto;
    display: block;
    height: auto;
    max-width: 100%;
}

The code I'm using to generate the .docx is available here, guided from this question. Thanks!

Community
  • 1
  • 1
FranciscoBouza
  • 590
  • 6
  • 19
  • I think `div` tags are just rendered as paragraphs when you import them aren't they? So I wouldn't be sure that all style attributes would be honoured (e.g. centering a container). – Ben Dec 01 '14 at 12:50
  • @Ben leaving the images alone without a 'div' inside them didn't change anything... Tried putting them right inside the 'body' tag, and still no centered... – FranciscoBouza Dec 01 '14 at 13:18
  • I'm not sure I understand. I'm saying I'm not aware of any code which will take a div centred by CSS, and ensure it remains centred when parsed into an OpenXML paragraph entity. You may need to post-process the generated paragraph/ inline image in docx4j to ensure it's centred in the docx file. – Ben Dec 01 '14 at 19:36
  • I was thinking I may do so... Do you know how could I post-process it? I guess it would have something to do with an id set to it... Thank you! – FranciscoBouza Dec 01 '14 at 23:36

1 Answers1

2

Testing with code at https://github.com/plutext/docx4j-ImportXHTML (I didn't try v3.2.1), the following works for me:

    String xhtml= "<div align=\"center\">" +
                "<img src='" + PNG_IMAGE_DATA + "'  />" +
            "</div>"; 

or

    String xhtml= "<div align=\"center\">" +
                "<p><img src='" + PNG_IMAGE_DATA + "'  /></p>" +
            "</div>"; 

I didn't try putting the align attribute on the image itself.

I note Center image using text-align center? but haven't tried:

display: block;
margin-left: auto;
margin-right: auto;

Getting that to work might well require a code patch.

Community
  • 1
  • 1
JasonPlutext
  • 15,352
  • 4
  • 44
  • 84
  • Genius! First choice didn't work (that was what I was doing), but the second one (the one using P) worked like a charm! Thanks pal! – FranciscoBouza Dec 02 '14 at 12:24