Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

docx4j replace variable with html

Tags:

java

xhtml

docx4j

i got this sample code to replace variables with text and it works perfect.

WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File("c:/template.docx"));

VariablePrepare.prepare(wordMLPackage);

MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();            

HashMap<String, String> mappings = new HashMap<String, String>();
mappings.put("firstname", "Name"); //${firstname}
mappings.put("lastname", "Name"); //${lastname}

documentPart.variableReplace(mappings);

wordMLPackage.save(new java.io.File("c:/replace.docx"));

but now i have to replace the variables with html. I tried something like this. but of cause it does not work

WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.load(new java.io.File("c:/template.docx"));

VariablePrepare.prepare(wordMLPackage);

MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart();    

String html = "<html><head><title>Import me</title></head><body><p style='color:#ff0000;'>Hello World!</p></body></html>"; 

AlternativeFormatInputPart afiPart = new AlternativeFormatInputPart(new PartName("/hw.html"));
afiPart.setBinaryData(html.toString().getBytes());
afiPart.setContentType(new ContentType("text/html"));
Relationship altChunkRel = documentPart.addTargetPart(afiPart);
CTAltChunk ac = Context.getWmlObjectFactory().createCTAltChunk();
ac.setId(altChunkRel.getId());


HashMap<String, String> mappings = new HashMap<String, String>();
mappings.put("firstname", ac.toString()); //${firstname}
mappings.put("lastname", "Name"); //${lastname}

documentPart.variableReplace(mappings);

wordMLPackage.save(new java.io.File("c:/replace.docx"));

Is there any way to achieve this?

like image 854
Pudelduscher Avatar asked Jul 10 '26 05:07

Pudelduscher


1 Answers

The variable replacement stuff is all about swapping out simple values in WordML, it won't work for HTML.

You need to import (X)HTML into your Word document the correct way. In the latest version of docx4j, this is done via the ImportXHTML sub-project: https://github.com/plutext/docx4j-ImportXHTML (in earlier versions, the XHTML import code is part of the main docx4j project).

Essentially the code takes well-formed XHTML, parses it into WordML constructs (i.e. text elements, runs, paragraphs and so on), and then you can insert the resulting collection of objects into your Word file. An example:

// Where xhtml = String representing well-formed XHTML to insert
// Where pkg = your WordProcessingMLPackage instance
XHTMLImporterImpl importer = new XHTMLImporterImpl(pkg);
pkg.getMainDocumentPart().getContent().addAll(importer.convert(xhtml, null));
like image 77
Ben Avatar answered Jul 14 '26 17:07

Ben



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!