【问题标题】:DOCX4J: Converting HTML to Docx - Table FormattingDOCX4J:将 HTML 转换为 Docx - 表格格式
【发布时间】:2016-03-22 10:49:07
【问题描述】:

我正在将 DocX 转换为 Html 并返回到 DocX。最终 Docx 成功生成。但是,转换会扭曲最终文档中表格的格式。最终docx中生成的表格的单元格宽度变长了,导致表格超出了文档的边界。

  • docx中的原始表格列宽8.15厘米(表格宽度,16.30厘米)。
  • 转换为 html 的表格宽度:6.42 英寸。
  • 转换回 docx 表格列宽为 10.76 厘米(表格 宽度,21.52 厘米)。

有没有办法让我在转换后保持相同的格式? 非常感谢任何建议。

下面是我的代码:

    private void convertHtmlToDocx() throws IOException, JAXBException, Docx4JException{
        //convert back to docx 

        String inputfilepath = System.getProperty("user.dir") + "myPath";
        String baseURL = "file:///"+System.getProperty("user.dir")+"path";

        String stringFromFile = FileUtils.readFileToString(new File(inputfilepath), "UTF-8");

        String unescaped = stringFromFile;
        if (stringFromFile.contains("</") ) {
            unescaped = StringEscapeUtils.unescapeHtml(stringFromFile);         
        }      

        System.out.println("Unescaped: " + unescaped);

        // Setup font mapping
        RFonts rfonts = Context.getWmlObjectFactory().createRFonts();
        rfonts.setAscii("Century Gothic");
        XHTMLImporterImpl.addFontMapping("Century Gothic", rfonts);

        // Create an empty docx package
        WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage.createPackage();

        NumberingDefinitionsPart ndp = new NumberingDefinitionsPart();
        wordMLPackage.getMainDocumentPart().addTargetPart(ndp);
        ndp.unmarshalDefaultNumbering();        

        // Convert the XHTML, and add it into the empty docx we made
        XHTMLImporterImpl XHTMLImporter = new XHTMLImporterImpl(wordMLPackage);
        XHTMLImporter.setTableFormatting(FormattingOption.IGNORE_CLASS);
        XHTMLImporter.setParagraphFormatting(FormattingOption.IGNORE_CLASS);
        XHTMLImporter.setHyperlinkStyle("Hyperlink");
        wordMLPackage.getMainDocumentPart().getContent().addAll(XHTMLImporter.convert(unescaped, baseURL) );


        wordMLPackage.save(new java.io.File(System.getProperty("user.dir") + "myPath") );

    }

【问题讨论】:

    标签: java docx4j


    【解决方案1】:

    您的用例是否通过 XHTML 往返进行基于 Web 的编辑?

    如果是这样,也许docx-html-editor 会有所帮助。它通过保存往返过程中使用的状态/提示来工作。

    除此之外,Word 中的表格要么是固定的单元格宽度,要么不是。您描述的行为是否发生在固定宽度的表格中?

    固定宽度应该没问题(或者很容易做到)。不固定更难...

    【讨论】:

    • 是的。这正是我的用例。是的,表格宽度是固定的。我浏览了手册,我有几个问题。如果我要使用这个库,我还需要将 docx 转换为 html,然后再转换回 docx 吗?我使用 primefaces 作为我的前端,它有 CKEditor。我是使用 primefaces 提供的还是必须安装它?
    • Project github.com/plutext/docx-html-editor 进行转换。尝试独立运行它,一旦你开始工作,将它集成到你的项目中。正如页面所说,它使用CKeditor v3.6.6.1,所以我猜primefaces提供的那个如果接近的话可能会工作。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-06-15
    • 1970-01-01
    • 1970-01-01
    • 2012-06-23
    • 2013-12-26
    • 1970-01-01
    • 2011-02-07
    相关资源
    最近更新 更多