2017-02-24 287 views
0

我有這個字符串:Docx4j換行符在字符串

Prueba 
Lista: 
- li1 
- li2 
- li3 
- li4 

       Tabulado 
       Tabulado     Tabulado     Tabulado     Tabulado 
       Tabulado     Tabulado     Tabulado     Tabulado     Tabulado     Tabulado 
       Tabulado     Tabulado     Tabulado     Tabulado     Tabulado     Tabulado     Tabulado     Tabulado 

但是當我準備我的.docx的字符串打印:

Prueba Listas: - li1 - li2 - li3 - li4 Tabulado Tabulado Tabulado Tabulado Tabulado Tabulado Tabulado Tabulado Tabulado 
Tabulado Tabulado Tabulado Tabulado Tabulado Tabulado Tabulado Tabulado Tabulado Tabulado 

這裏是我得到的字符串:

String escDesc = report.getDescription(); 
if (escDesc.contains("\n")){ 
    //escDesc = escDesc.replaceAll("\\n", System.getProperty("line.separator")); 
    //escDesc = escDesc.replaceAll("\\n", "<w:br/>"); 
} 
escDesc = StringEscapeUtils.escapeXml(escDesc); 

valuesAdd.put("DESCRIPCION", escDesc); 

這裏是我添加的所有variebles:

private void replacePlaceholders() 
     throws Exception { 

    MainDocumentPart documentPart = wordMLPackage.getMainDocumentPart(); 

    VariablePrepare.prepare(wordMLPackage); 

    documentPart.variableReplace(valuesAdd); 

    List<SectionWrapper> sectionWrappers = wordMLPackage.getDocumentModel().getSections(); 
    String xml = null; 

    for (SectionWrapper sw : sectionWrappers) { 
    HeaderFooterPolicy hfp = sw.getHeaderFooterPolicy(); 

    if (hfp != null) { 

     HeaderPart headerPart = hfp.getDefaultHeader(); 

     if (headerPart != null) { 
      xml = XmlUtils.marshaltoString(headerPart.getJaxbElement()); 
     } 


    Object obj = null; 
    try { 
     obj = XmlUtils.unmarshallFromTemplate(xml, valuesAdd); 
    } catch (JAXBException e) { 
     e.printStackTrace(); 
    } 

    // Inject result into docx 
    headerPart.setJaxbElement((Hdr) obj); 
    } 
    } 
} 

我想保留\ n,但我不知道我現在必須做什麼,我希望有人可以給我一些提示。

這是一個System.out.println(escDesc);

enter image description here

而且這是在文檔中的字符串:

enter image description here 感謝。

回答

2

正如您可能已經想出的一樣,WordML對製表符和換行符(軟返回)使用不同的元素。

的XML看起來像:

 <w:r> 
      <w:t>Tabulado</w:t> 
      <w:tab/> 
      <w:t>Tabulado</w:t> 
      <w:br/> 
      <w:t>Tabulado</w:t> 
     </w:r> 

和相應的Java代碼:

  org.docx4j.wml.ObjectFactory wmlObjectFactory = new org.docx4j.wml.ObjectFactory(); 

      // Create object for tab (wrapped in JAXBElement) 
      R.Tab rtab = wmlObjectFactory.createRTab(); 
      JAXBElement<org.docx4j.wml.R.Tab> rtabWrapped = wmlObjectFactory.createRTab(rtab); 
      // Add it to the run... 
      run.getContent().add(rtabWrapped); 

      // Create object for br 
      Br br = wmlObjectFactory.createBr(); 

這是基礎。你可以用「TabuladoTabulado」來代替。

或者使用內容控制數據綁定或導入XHTML。