使用java applet查看.doc文件

时间:2012-08-27 13:27:29

标签: java ms-word applet

我有一个网络应用程序。我在服务器端生成了xml格式的MS Word文档(Word 2003 XML文档)。我需要使用某种查看器向客户端的用户显示此文档。所以,问题是:我可以使用哪些库来解决这个问题?我需要一个API来使用java 在客户端上查看word文档。

4 个答案:

答案 0 :(得分:4)

您无法使用Java(或任何其他简单技术)在网页中可靠地显示Word文档。有几个商业图书馆用于呈现Word,但您不会发现这些是简单,廉价或可靠的解决方案。

您应该做的是以下内容:

(1)使用.NET程序在服务器上打开Word引擎 (2)使用Word引擎将文档转换为RTF (3)使用RTF Swing小部件显示富文本,或转换为HTML:

String rtf = [your document rich text];
BufferedReader input = new BufferedReader(new StringReader(rtf));

RTFEditorKit rtfKit = new RTFEditorKit();
StyledDocument doc = (StyledDocument) rtfKit.createDefaultDocument();
rtfEdtrKt.read( input, doc, 0 );
input.close();

HTMLEditorKit htmlKit = new HTMLEditorKit();       
StringWriter output = new StringWriter();
htmlKit.write( output, doc, 0, doc.getLength());

String html = output.toString();

此方法的主要风险是Word引擎崩溃或内存泄漏。因此,您必须有一种机制,可以定期重新启动它并对其进行测试以确保它正常运行并且不会占用内存。

答案 1 :(得分:1)

docx4all是一个基于Swing的applet,它执行几年前我们写的Word 2007 XML(即不是Word 2003 XML)。

svn获取。

这是一种可行的编辑方法。如果您想要的只是一个查看器,而不是转换为HTML或PDF?您可以使用docx4j。 (披露:“我的”项目)。

答案 2 :(得分:1)

您可以查看能够阅读各种word文档的Apache POI - Java API to Handle Microsoft Word Files(分别是OLE2和OOXML格式,.doc和.docx扩展名)。

阅读doc文件可以很简单:

import java.io.*;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;

public class ReadDocFile {
public static void main(String[] args) {
File file = null;
WordExtractor extractor = null ;
try {

file = new File("c:\\New.doc");
FileInputStream fis=new FileInputStream(file.getAbsolutePath());
HWPFDocument document=new HWPFDocument(fis);
extractor = new WordExtractor(document);
String [] fileData = extractor.getParagraphText();
for(int i=0;i<fileData.length;i++){
if(fileData[i] != null)
System.out.println(fileData[i]);
}
}
catch(Exception exep){}
}
}

您可以在HWPF Quick-Guide(特别是HWPF unit tests

找到更多信息

请注意,根据POI网站:

  

HWPF仍处于早期发展阶段。

答案 3 :(得分:0)

我建议查看openoffice源代码并实现它。 它应该用java编写。