Writing HTML Content Into MS WORD Using JAVA?
I am developing an Exam Software in which I have used Subscript and superscript. so I have to store the Questions in HTML in the Database, Now i want to write those questions with
Solution 1:
You can add your HTML as an AltChunk, and have Word convert it to native docx content when the file is first opened.
If you need to convert to native docx content in Java, you can use docx4j-ImportXHTML
Disclosure: I manage that repo.
Solution 2:
Using java api docx4j-ImportXHTML that can be achieved by below method:
public static void xhtmlToDocx(String destinationPath, String fileName)
{
File dir = new File (destinationPath);
File actualFile = new File (dir, fileName);
WordprocessingMLPackage wordMLPackage = null;
try
{
wordMLPackage = WordprocessingMLPackage.createPackage();
}
catch (InvalidFormatException e)
{
e.printStackTrace();
}
XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(wordMLPackage);
OutputStream fos = null;
try
{
fos = new ByteArrayOutputStream();
System.out.println(XmlUtils.marshaltoString(wordMLPackage
.getMainDocumentPart().getJaxbElement(), true, true));
HTMLSettings htmlSettings = Docx4J.createHTMLSettings();
htmlSettings.setWmlPackage(wordMLPackage);
Docx4jProperties.setProperty("docx4j.Convert.Out.HTML.OutputMethodXML",
true);
Docx4J.toHTML(htmlSettings, fos, Docx4J.FLAG_EXPORT_PREFER_XSL);
wordMLPackage.save(actualFile);
}
catch (Docx4JException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
finally{
try {
fos.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
To add dependency docx4j-ImportXHTML, use(3.3.1 is latest version while I am writing this answer. If you seeing it later use latest stable version of your time).
<dependency>
<groupId>org.docx4j</groupId>
<artifactId>docx4j-ImportXHTML</artifactId>
<version>3.3.1</version>
</dependency>
Post a Comment for "Writing HTML Content Into MS WORD Using JAVA?"