Search code examples
javaxhtmldocx4j

Docx4j ImportXHTML: Hyperlink around image not working


I want to add a image in my Word doc using docx4j lib. When click on that image i want to open a link. But not able to open the link. Also the link is visible in my document (it should be hidden as per my HTML/CSS). I am using xhtml to convert the html to openxml.

My css for the image is as follows :

  

      <a href="https://www.google.com">
          <img id="custom_file_logo" style="width:40px;height:20px;" name="Google Logo" 
                     src="https://myxyzdomain.com/image8-2.jpg" 
                     />

My generated doc is visible as follows : enter image description here

I want to hide the link and want to open it after click on the image.

Java code is as follows :

String htmlString = "<a href=\"https://www.google.com\">\r\n"
                    + "  <img id=\"custom_file_logo\" style=\"width:40px;height:20px;\" name=\"Google Logo\" \r\n"
                    + "          src=\"https://myxyzdomain.com/image8-2.jpg\" \r\n"
                    + "             />";
            
            WordprocessingMLPackage wordPackage = WordprocessingMLPackage.createPackage();
            MainDocumentPart mainDocumentPart = wordPackage.getMainDocumentPart();
            
            XHTMLImporterImpl xHTMLImporter = new XHTMLImporterImpl(wordPackage);
            String html = convertToXhtml(htmlString);
            html = html.replace("&nbsp;", "\u00A0");
            wordPackage.getMainDocumentPart().getContent().addAll(xHTMLImporter.convert(html, null));
            File exportFile = new File("xyz.docx");
            wordPackage.save(exportFile)

Solution

  • We need to add support for importing a hyperlink surrounding an image.

    Now tracking at https://github.com/plutext/docx4j-ImportXHTML/issues/83

    A hyperlinked image contains an a:hlinkClick element, for example:

        <w:drawing>
          <wp:inline distT="0" distB="0" distL="0" distR="0" wp14:anchorId="4FD4236C" wp14:editId="010E5646">
            <wp:docPr id="1" name="Picture 1" descr="Diagram&#xA;&#xA;Description automatically generated">
              <a:hlinkClick xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main" r:id="rId4"/>
            </wp:docPr>