docx4j преобразование html- ›docx-› html

Я работаю над своим первым проектом с использованием docx4j ... Моя цель - экспортировать xhtml из веб-приложения (ckeditor created html) в docx, отредактировать его в Word, а затем импортировать обратно в ckeditor wysiwyg.

(* crosspost из http://www.docx4java.org/forums/xhtml-import-f28/html-docx-html-inserts-a-lot-of-space-t1966.html#p6791?sid=78b64a02482926c4dbdbafbf50d0a914 обновится после ответа)

Я создал тестовый html-документ со следующим содержанием:

<html><ul><li>TEST LINE 1</li><li>TEST LINE 2</li></ul></html>

Затем мой код создает документ docx из этого HTML, например: WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage .createPackage ();

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

    XHTMLImporterImpl xHTMLImporter = new XHTMLImporterImpl(wordMLPackage);
    xHTMLImporter.setHyperlinkStyle("Hyperlink");

    wordMLPackage.getMainDocumentPart().getContent()
            .addAll(xHTMLImporter.convert(new File("test.html"), null));

    System.out.println(XmlUtils.marshaltoString(wordMLPackage
            .getMainDocumentPart().getJaxbElement(), true, true));

    wordMLPackage.save(new java.io.File("test.docx"));

Затем мой код пытается преобразовать docx BACK в html следующим образом: WordprocessingMLPackage wordMLPackage = WordprocessingMLPackage .createPackage ();

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

    XHTMLImporterImpl xHTMLImporter = new XHTMLImporterImpl(wordMLPackage);
    xHTMLImporter.setHyperlinkStyle("Hyperlink");

    WordprocessingMLPackage docx = WordprocessingMLPackage.load(new File("test.docx"));
    AbstractHtmlExporter exporter = new HtmlExporterNG2();
    OutputStream os = new java.io.FileOutputStream("test.html");
    HTMLSettings htmlSettings = new HTMLSettings();
    javax.xml.transform.stream.StreamResult result = new javax.xml.transform.stream.StreamResult(
            os);
    exporter.html(docx, result, htmlSettings);

Возвращенный html:

<?xml version="1.0" encoding="UTF-8"?><html xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
<head>
<META http-equiv="Content-Type" content="text/html; charset=UTF-8">
<meta content="text/html; charset=utf-8" http-equiv="Content-Type">
<style>
<!--/*paged media */ div.header {display: none }div.footer {display: none } /*@media print { */@page { size: A4; margin: 10%; @top-center {content: element(header) } @bottom-center {content: element(footer) } }/*element styles*/ .del  {text-decoration:line-through;color:red;} .ins {text-decoration:none;background:#c0ffc0;padding:1px;}
 /* TABLE STYLES */ 

 /* PARAGRAPH STYLES */ 
.DocDefaults {display:block;margin-bottom: 4mm;line-height: 115%;font-size: 11.0pt;}
.Normal {display:block;}

 /* CHARACTER STYLES */ span.DefaultParagraphFont {display:inline;}
-->
</style>
<script type="text/javascript">
<!--function toggleDiv(divid){if(document.getElementById(divid).style.display == 'none'){document.getElementById(divid).style.display = 'block';}else{document.getElementById(divid).style.display = 'none';}}
--></script>
</head>
<body>

  <!-- userBodyTop goes here -->




<div class="document">


<p class="Normal DocDefaults " style="text-align: left;position: relative; margin-left: 17mm;text-indent: -0.25in;margin-bottom: 0in;">&bull;  <span class="DefaultParagraphFont " style="font-weight: normal;color: #000000;font-style: normal;font-size: 11.0pt;">TEST LINE 1</span>
</p>


<p class="Normal DocDefaults " style="text-align: left;position: relative; margin-left: 17mm;text-indent: -0.25in;margin-bottom: 0in;">&bull;  <span class="DefaultParagraphFont " style="font-weight: normal;color: #000000;font-style: normal;font-size: 11.0pt;">TEST LINE 2</span>
</p>
</div>







  <!-- userBodyTail goes here -->


</body>
</html>

Теперь после каждой строки создается много дополнительного места. Не уверен, почему это происходит, преобразование, похоже, добавляет много лишних пробелов / возвратов каретки.


person Morgan Dowell    schedule 25.08.2014    source источник


Ответы (2)


Из вашего вопроса неясно, беспокоит ли вас пробел в исходном документе (X) HTML или на вашей странице при отображении (предположительно в CKEditor). Если последнее, то могут быть актуальны браузер и версия СК.

Пробелы могут быть или не быть значимыми; попробуйте погуглить "значимые пробелы xhtml" для получения дополнительной информации.

В качестве фона, в зависимости от свойства docx4j docx4j.Convert.Out.HTML.OutputMethodXML, docx4j будет использовать

<xsl:output method="html" encoding="utf-8" omit-xml-declaration="no" indent="no" 
doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
      doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/>

or

  <xsl:output method="xml" encoding="utf-8" omit-xml-declaration="no" indent="no" 
        doctype-public="-//W3C//DTD XHTML 1.0 Transitional//EN"
        doctype-system="http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"/>

Обратите внимание на различие в значении @method. Если вам нужно что-то другое, вы можете изменить docx2html.xsl или docx2xhtml.xsl соответственно.

person JasonPlutext    schedule 25.08.2014
comment
Спасибо, Джейсон. Извините, если я не понял, проблема с пробелом возникла после преобразования docx- ›xhtml. Ckeditor рассматривает это как значительное пустое пространство. - person Morgan Dowell; 26.08.2014

Есть ли способ преобразовать wordMLPackage в html без лишних вещей вроде:

<?xml version="1.0" encoding="UTF-8"?>

а CSS?

Может ли это быть что-то простое, как исходный html и встроенный CSS, например <html><body><div style="...."></div></body></html>?

person David Z.    schedule 16.09.2014
comment
Возможно, вы захотите спросить об этом в своем собственном сообщении ... Я считаю, что docx4j сгенерирует правильный xhtml, что означает тег xml вверху, заголовок и некоторые другие элементы ... Я проанализировал документ с помощью javascript и отформатировал его, используя импорт CKEditor из word »для форматирования результатов преобразования docx4j в xhtml. - person Morgan Dowell; 26.09.2014