Reputation: 8261
I would like to convert either an HTML or MXML file document to Microsoft .doc and/or .docx format.
Please provide an example for doing this?
Upvotes: 1
Views: 18364
Reputation: 939
You can convert HTML to DOCX using Aspose.Words Cloud SDK for Java. Its free pricing plan offers 150 free API calls per month.
P.S: I am a developer evangelist at Aspose
//Get Client ID and Client Key from https://dashboard.aspose.cloud/
WordsApi wordsApi = new WordsApi("xxxxxxx-xxxx-xxxx-xxxx-xxxxxxxx","xxxxxxxxxxxxxxxxxxxxxxx","https://api.aspose.cloud");
ApiClient client = wordsApi.getApiClient();
client.setConnectTimeout(12*60*1000);
client.setReadTimeout(12*60*1000);
client.setWriteTimeout(12*60*1000);
try {
ConvertDocumentRequest request = new ConvertDocumentRequest(
Files.readAllBytes(Paths.get("C:/Temp/02_pages.html").toAbsolutePath()),
"docx",
null,
null,
null,
null
);
File result = wordsApi.convertDocument(request);
System.out.println("api request completed...");
File dest = new File("C:/Temp/02_pages_java.docx");
Files.copy(result.toPath(), dest.toPath(),
java.nio.file.StandardCopyOption.REPLACE_EXISTING);
} catch (Exception e) {
System.out.println(e.getMessage());
}
Upvotes: 0
Reputation: 915
You can also use docx4j.jar which simply converts xhtml to docx.
You can save your format information as xhtml template and place input from form (like name,age,address etc) into the template at runtime.
This is a sample code to refer from this link
public static void main(String[] args) throws Exception
{
String xhtml=
"<table border=\"1\" cellpadding=\"1\" cellspacing=\"1\" style=\"width:100%;\"><tbody><tr><td>test</td><td>test</td></tr><tr><td>test</td><td>test</td></tr><tr><td>test</td><td>test</td></tr></tbody></table>";
// To docx, with content controls
WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();
XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(wordMLPackage);
wordMLPackage.getMainDocumentPart().getContent().addAll(
XHTMLImporter.convert( xhtml, null) );
wordMLPackage.save(new java.io.File("D://sample.docx"));
}
Upvotes: 5
Reputation: 6223
You can use both iText and Apache POI to handle and convert MS doc in Java.
Upvotes: 0
Reputation: 3409
I've found that by far the best (free) option to do conversions like this is to use the OpenOffice API. It has a very robust conversion facility. It's a bit of a pain to initially get working because of how abstract the API is, but once you do, it's powerful. This API wrapper helps to simplify it somewhat.
Upvotes: 6