开发者

Convert HTML/MXML file to Word doc programmatically in Java

I would like to convert eith开发者_开发百科er an HTML or MXML file document to Microsoft .doc and/or .docx format.

Please provide an example for doing this?


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.


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"));
}


You can use both iText and Apache POI to handle and convert MS doc in Java.


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());
        }

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜