Instead of rendering tables and other html tags in docx these are saved as plain text using docx4j-ImportXHTML

纵然是瞬间 提交于 2019-11-29 15:53:15

I corrected my code as below:

  1. Use ByteArrayStream instead of FileOutputStream i.e.

Instead of

fos = new FileOutputStream(actualFile);
            wordMLPackage.getMainDocumentPart().getContent().addAll( 
                    XHTMLImporter.convert( xhtml, null) );

Use:

fos = new ByteArrayOutputStream();
  1. Add wordMLPackage.save(actualFile)

Full code:

public static void xhtmlToDocx1(String xhtml, 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();
            }
        }
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!