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:
publicstaticvoidxhtmlToDocx(String destinationPath, String fileName)
{
Filedir=newFile (destinationPath);
FileactualFile=newFile (dir, fileName);
WordprocessingMLPackagewordMLPackage=null;
try
{
wordMLPackage = WordprocessingMLPackage.createPackage();
}
catch (InvalidFormatException e)
{
e.printStackTrace();
}
XHTMLImporterImplXHTMLImporter=newXHTMLImporterImpl(wordMLPackage);
OutputStreamfos=null;
try
{
fos = newByteArrayOutputStream();
System.out.println(XmlUtils.marshaltoString(wordMLPackage
.getMainDocumentPart().getJaxbElement(), true, true));
HTMLSettingshtmlSettings= 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?"