2014-09-21 81 views
4

我需要HTML轉換爲RTF,而我使用此代碼:在Java中將HTML轉換爲RTF?

private static String convertToRTF(String htmlStr) { 

     OutputStream os = new ByteArrayOutputStream(); 
     HTMLEditorKit htmlEditorKit = new HTMLEditorKit(); 
     RTFEditorKit rtfEditorKit = new RTFEditorKit(); 
     String rtfStr = null; 

     htmlStr = htmlStr.replaceAll("<br.*?>", "#NEW_LINE#"); 
     htmlStr = htmlStr.replaceAll("</p>", "#NEW_LINE#"); 
     htmlStr = htmlStr.replaceAll("<p.*?>", ""); 
     InputStream is = new ByteArrayInputStream(htmlStr.getBytes()); 
     try { 
      Document doc = htmlEditorKit.createDefaultDocument(); 
      htmlEditorKit.read(is, doc, 0); 
      rtfEditorKit.write(os, doc, 0, doc.getLength()); 
      rtfStr = os.toString(); 
      rtfStr = rtfStr.replaceAll("#NEW_LINE#", "\\\\par "); 
     } catch (IOException e) { 
      e.printStackTrace(); 
     } catch (BadLocationException e) { 
      e.printStackTrace(); 
     } 
     return rtfStr; 
    } 

問題是,當我嘗試轉換的HTML有項目符號或編號是這樣的:

  1. 一個

這是HTML:

<html><head> 
    <style> 
     <!-- 
     --> 
    </style> 
    </head> 
    <body contenteditable="true"> 
    <p style="text-align: left;"> 
     <ol> 
      <li><font face="'Segoe UI'">one</font></li> 
      <li><font face="'Segoe UI'">two</font></li> 
     </ol> 
    </p> 

,這將轉換結果:

ONETWO

RTF

{\rtf1\ansi 
{\fonttbl\f0\fnil Monospaced;\f1\fnil 'Segoe UI';} 

\par 
\f1 one\f1 two\par \par 
} 

如何轉換數字/子彈?

+1

@JimGarrison是的,我做到了!我無法找到任何解決方案,在Java代碼! – 2014-09-21 07:26:21

+0

1.您的'\ par's關閉。 2.你想跟蹤正確的數字並將它們作爲文本插入,還是你想使用RTF列表來自動編號? (後者被稱爲'\ listlevel'。) – usr2564301 2014-09-21 09:51:28

+0

@Jongware作爲文本! – 2014-09-21 10:00:12

回答

2

這些庫可能會有所幫助:

+1

雖然這個鏈接可能回答這個問題,但最好在這裏包含答案的重要部分,並提供供參考的鏈接。如果鏈接頁面更改,則僅鏈接答案可能會失效。 – 2014-09-28 19:25:15

+0

@ElectricCoffee此用戶不發佈文章的鏈接,其內容在答案中是有意義的;這不僅僅是一個*鏈接*答案,本身。 – Qix 2014-10-05 18:31:45

+1

我可以看到使用Apache FOP從html到rtf的轉換工作示例嗎? – umar 2016-02-18 10:46:13