word解析为html文本 并替换内容图片(doc、docx

我们的需求是上传word并把word内容返回到当前页面富文本框,网上看了好多 也试过直接用poi解析

感觉直接解析就是个坑word各种格式够玩一年的。。

这里是把word转成html再读取 主要代码如下:

public static String docToHtml(File file) throws Exception {
		HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(file));
		Document document = DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument();
		WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(document);
		// 保存图片,并返回图片的相对路径
		wordToHtmlConverter.setPicturesManager((content, pictureType, name, width, height) -> {
			File imgfile = new File(name);
			OutputStream output = null;
			BufferedOutputStream bufferedOutput = null;
			try {
				output = new FileOutputStream(imgfile);
				bufferedOutput = new BufferedOutputStream(output);
				bufferedOutput.write(content);
			} catch (Exception e) {
				e.printStackTrace();
			} finally {
				try {
					bufferedOutput.close();
					output.close();
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
			String url = OSSUnit.uploadObject2OSS(imgfile);
			imgfile.delete();
			return url;
		});
		wordToHtmlConverter.processDocument(wordDocument);
		Document htmlDocument = wordToHtmlConverter.getDocument();
		DOMSource domSource = new DOMSource(htmlDocument);
		File htmlFile = new File(Global.getUserfilesBaseDir()+IdWorker.getIdStr()+".html");
		StreamResult streamResult = new StreamResult(htmlFile);
		TransformerFactory tf = TransformerFactory.newInstance();
		Transformer serializer = tf.newTransformer();
		serializer.setOutputProperty(OutputKeys.ENCODING, "utf-8");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		serializer.setOutputProperty(OutputKeys.METHOD, "html");
		serializer.transform(domSource, streamResult);
		String sCurrentLine="";
		String sTotalString="";
		java.io.BufferedReader l_reader = new java.io.BufferedReader(
				new java.io.InputStreamReader(new FileInputStream(htmlFile)));
		while ((sCurrentLine = l_reader.readLine()) != null) {
			sTotalString += sCurrentLine ;//+ "/r/n"
			 System.out.println(sCurrentLine);
		}
		l_reader.close();
		htmlFile.delete();
		return sTotalString;
	}

	// docx转换为html
	public static String docxToHtml(File file) throws Exception {
//		OutputStreamWriter outputStreamWriter = null;
		try {
			XWPFDocument document = new XWPFDocument(new FileInputStream(file));
//			XHTMLOptions options = XHTMLOptions.create();
            // 2) Prepare XHTML options (here we set the IURIResolver to  
            // load images from a "word/media" folder)  
            File imageFolderFile = new File(Global.getUserfilesBaseDir()+"11");  
            XHTMLOptions options = XHTMLOptions.create().URIResolver(  
                    new FileURIResolver(imageFolderFile));  
            options.setExtractor(new FileImageExtractor(imageFolderFile));
			// 存放图片的文件夹
//			options.setExtractor(new FileImageExtractor(new File(Global.getUserfilesBaseDir())));
			// html中图片的路径
//			options.URIResolver(new BasicURIResolver("image"));
			String descFileName = Global.getUserfilesBaseDir()+IdWorker.getIdStr()+".html";
			FileUtils.createFile(descFileName);
			File htmlFile = new File(descFileName);
//			outputStreamWriter = new OutputStreamWriter(new FileOutputStream(htmlFile), "utf-8");
			XHTMLConverter.getInstance().convert(document, new FileOutputStream(htmlFile), options);
			
			String sCurrentLine="";
			String sTotalString="";
			java.io.BufferedReader l_reader = new java.io.BufferedReader(
					new java.io.InputStreamReader(new FileInputStream(htmlFile)));
			while ((sCurrentLine = l_reader.readLine()) != null) {
				sTotalString += sCurrentLine ;//+ "/r/n"
				 System.out.println(sCurrentLine);
			}
			l_reader.close();
			htmlFile.delete();
			return CmsUtils.contentReImg(sTotalString,"1");
		} finally {
//			if (outputStreamWriter != null) {
//				outputStreamWriter.close();
//			}
		}
	}



  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
你可以使用Apache POI库来解析Word文档并替换其中的内容。下面是一个简单的示例代码: ```java import java.io.FileInputStream; import java.io.FileOutputStream; import org.apache.poi.xwpf.usermodel.*; import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTR; public class WordReplace { public static void main(String[] args) { try { // 读取Word文档 XWPFDocument doc = new XWPFDocument(new FileInputStream("input.docx")); // 遍历文档中的所有段落 for (XWPFParagraph para : doc.getParagraphs()) { // 遍历段落中的所有文本 for (XWPFRun run : para.getRuns()) { String text = run.getText(0); if (text != null && text.contains("要替换内容")) { // 替换文本 text = text.replace("要替换内容", "替换后的内容"); run.setText(text, 0); } } } // 遍历文档中的所有表格 for (XWPFTable table : doc.getTables()) { // 遍历表格中的所有行 for (XWPFTableRow row : table.getRows()) { // 遍历行中的所有单元格 for (XWPFTableCell cell : row.getTableCells()) { // 遍历单元格中的所有段落 for (XWPFParagraph para : cell.getParagraphs()) { // 遍历段落中的所有文本 for (XWPFRun run : para.getRuns()) { String text = run.getText(0); if (text != null && text.contains("要替换内容")) { // 替换文本 text = text.replace("要替换内容", "替换后的内容"); run.setText(text, 0); } } } } } } // 保存修改后的Word文档 doc.write(new FileOutputStream("output.docx")); doc.close(); } catch (Exception ex) { ex.printStackTrace(); } } } ``` 这段代码可以替换Word文档中所有段落和表格中的指定文本。你只需要将其中的“要替换内容”和“替换后的内容替换成你需要的内容即可。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值