在线预览doc,docx文档

在线预览doc,docx文档

前言:上传成功以后的每个文档都能获取到所传文件的路径;

我这里是一个maven项目,需要在pom文件引入

<!-- 文件预览 -->
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi</artifactId>
			<version>3.15</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-scratchpad</artifactId>
			<version>3.15</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml</artifactId>
			<version>3.15</version>
		</dependency>
		<dependency>
			<groupId>fr.opensagres.xdocreport</groupId>
			<artifactId>xdocreport</artifactId>
			<version>1.0.6</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>poi-ooxml-schemas</artifactId>
			<version>3.15</version>
		</dependency>
		<dependency>
			<groupId>org.apache.poi</groupId>
			<artifactId>ooxml-schemas</artifactId>
			<version>1.3</version>
		</dependency>
		
		<dependency>
	       <groupId>com.alibaba</groupId>
	       <artifactId>fastjson</artifactId>
	       <version>1.2.3</version>
		</dependency>

点击在线预览的时候,前端需要给后台传入这条数据的id
需要在你项目的static/img下边新建一个doc文件夹,存放所需要的文档;里面的图片 如图:

在线预览doc,docx文档_第1张图片
先将所需要的东西封装好

package com.xxxxx.xxxx.controller.tool;

import java.io.BufferedWriter;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.util.List;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.transform.OutputKeys;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;

import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.converter.PicturesManager;
import org.apache.poi.hwpf.converter.WordToHtmlConverter;
import org.apache.poi.hwpf.usermodel.Picture;
import org.apache.poi.hwpf.usermodel.PictureType;
import org.apache.poi.xwpf.converter.core.BasicURIResolver;
import org.apache.poi.xwpf.converter.core.FileImageExtractor;
import org.apache.poi.xwpf.converter.xhtml.XHTMLConverter;
import org.apache.poi.xwpf.converter.xhtml.XHTMLOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.w3c.dom.Document;

public class Doc2Html {

	/**
	 * doc转换为html
	 * 
	 * 
	 * @param
	 * 
	 * 			fileName
	 * 
	 *            docx文件路径(如果你的是存到文件服务器的,直接用路径,如果是直接将文件流存到数据库的,转为InputStream )
	 * 
	 * @param
	 * 
	 * 			outPutFile
	 * 
	 *            html输出文件路径
	 * 
	 * @throws TransformerException
	 * @throws IOException
	 * @throws ParserConfigurationException
	 */
	public static void doc2Html(String fileName, String outPutFile, String imgPath)
			throws TransformerException, IOException, ParserConfigurationException {
		long startTime = System.currentTimeMillis();
		// HWPFDocument wordDocument = new HWPFDocument(fileName);
		HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(fileName));
		WordToHtmlConverter wordToHtmlConverter = new WordToHtmlConverter(
				DocumentBuilderFactory.newInstance().newDocumentBuilder().newDocument());
		wordToHtmlConverter.setPicturesManager(new PicturesManager() {
			public String savePicture(byte[] content, PictureType pictureType, String suggestedName, float widthInches,
					float heightInches) {
				return "/img/doc/" + suggestedName;
			}
		});
		wordToHtmlConverter.processDocument(wordDocument);
		// 保存图片
		List<Picture> pics = wordDocument.getPicturesTable().getAllPictures();

		if (pics != null) {
			for (int i = 0; i < pics.size(); i++) {
				Picture pic = (Picture) pics.get(i);

				String suggestFullFileName = pic.suggestFullFileName();
				System.out.println(suggestFullFileName);
				try {
					pic.writeImageContent(new FileOutputStream(
							imgPath + "/src/main/resources/static/img/doc/" + pic.suggestFullFileName()));
				} catch (FileNotFoundException e) {
					e.printStackTrace();
				}
			}
		}

		Document htmlDocument = wordToHtmlConverter.getDocument();
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		DOMSource domSource = new DOMSource(htmlDocument);
		StreamResult streamResult = new StreamResult(out);

		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);
		out.close();
		writeFile(new String(out.toByteArray()), outPutFile);
		System.out.println("Generate " + outPutFile + " with " + (System.currentTimeMillis() - startTime) + " ms.");
	}

	/**
	 * 写文件
	 * 
	 * @param content
	 * @param path
	 */
	public static void writeFile(String content, String path) {
		FileOutputStream fos = null;
		BufferedWriter bw = null;
		try {
			File file = new File(path);
			fos = new FileOutputStream(file);
			bw = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"));
			bw.write(content);
		} catch (FileNotFoundException fnfe) {
			fnfe.printStackTrace();
		} catch (IOException ioe) {
			ioe.printStackTrace();
		} finally {
			try {
				if (bw != null)
					bw.close();
				if (fos != null)
					fos.close();
			} catch (IOException ie) {
			}
		}
	}

	/**
	 * docx格式word转换为html
	 * 
	 * @param fileName
	 *            docx文件路径(如果你的是存到文件服务器的,直接用路径,如果是直接将文件流存到数据库的,转为InputStream )
	 * @param outPutFile
	 *            html输出文件路径
	 * @throws TransformerException
	 * @throws IOException
	 * @throws ParserConfigurationException
	 */
	public static void docx2Html(String fileName, String outPutFile, String imgPath)
			throws TransformerException, IOException, ParserConfigurationException {
		String fileOutName = outPutFile;
		long startTime = System.currentTimeMillis();
		XWPFDocument document = new XWPFDocument(new FileInputStream(fileName));
		// XWPFDocument document = new XWPFDocument(fileName);
		XHTMLOptions options = XHTMLOptions.create().indent(4);
		// 导出图片
		File imageFolder = new File(imgPath + "/src/main/resources/static/img/");
		options.setExtractor(new FileImageExtractor(imageFolder));
		// URI resolver
		// options.URIResolver(new FileURIResolver(imageFolder));
		options.URIResolver(new BasicURIResolver("/img/"));
		File outFile = new File(fileOutName);
		outFile.getParentFile().mkdirs();
		OutputStream out = new FileOutputStream(outFile);
		XHTMLConverter.getInstance().convert(document, out, options);
		System.out.println("Generate " + fileOutName + " with " + (System.currentTimeMillis() - startTime) + " ms.");

	}

	public static void main(String[] args) throws Exception {
		// Doc2Html.docx2Html("D:\\测试文档.docx","D:\\cs.html");
	}

}

调用封装好的接口

public void devDoc(HttpServletResponse response, int kid) throws Exception {
		//获取项目的路径
		String realPath = System.getProperty("user.dir");
		Long kId = (long) kid;
		InputStream input = null;
		OutputStream out = null;
		CrKnowledge crKnowledge = crKnowledgeService.selectCrKnowledgeById(kId);
		CrKnowledgeAttach crKnowledgeAttach = new CrKnowledgeAttach();
		crKnowledgeAttach.setKUid(kId);
		crKnowledgeAttach.setFjName(crKnowledge.getKName());
		List<CrKnowledgeAttach> crKnowledgeAttachs = crKnowledgeAttachService
				.selectCrKnowledgeAttachList(crKnowledgeAttach);
		for (CrKnowledgeAttach crKnowledgeAttach2 : crKnowledgeAttachs) {
			crKnowledgeAttach.setFjUrl(crKnowledgeAttach2.getFjUrl());
			// 在线预览
			//获取文件路径
			String filePath = Global.getUploadPath();
			String string = crKnowledgeAttach2.getFjUrl().substring(15);
    		filePath+=string;
			//截取文件名称(查看获取到的文件名是否需要截取,这里需要全路径,需要截取)
			String filename = crKnowledgeAttach2.getFjName();
			String caselsh = filename.substring(0,filename.lastIndexOf("."));
			if (crKnowledgeAttach2.getFjTag1().equals("docx")) {
				Doc2Html.docx2Html(filePath, "D:\\"+caselsh+".html",realPath);
				input = new FileInputStream("D:\\"+caselsh+".html");
				response.setContentType("text/html;charset=UTF-8");// 解决页面显示乱码
				out = response.getOutputStream();
			} else if (crKnowledgeAttach2.getFjTag1().equals("doc")) {
				Doc2Html.doc2Html(filePath, "D:\\"+caselsh+".html",realPath);
				input = new FileInputStream("D:\\"+caselsh+".html");
				response.setContentType("text/html;charset=UTF-8");// 解决页面显示乱码
				out = response.getOutputStream();
			}
			FileInputStream fis = new FileInputStream("D:\\"+caselsh+".html");
			byte[] b = new byte[fis.available()];
			if (out != null) {
				if (input != null) {
					input.read(b);
					out.write(b);
				} else {
					System.out.println("InputStream为空。。。");
				}
			} else {
				System.out.println("OutputStream为空。。。");
			}

			out.flush();
			input.close();
			out.close();
		}
	}

前端需要传一个id直接展示就成:

在线预览doc,docx文档_第2张图片
这里我用ajax进行传值

$(function(){
			/* 获取到id进行传值 */
			var kid=[[${kid}]];
			var data={"kid":kid};
			$.ajax({
				type: "POST",
	            url: url+"xxx/xxxxxx/devDoc",
	            data: data,
	            dataType: 'text',
	            success: function(data) {
            		$("#div2").html(data);
	            }
			})
		})

效果图:
在线预览doc,docx文档_第3张图片
欢迎指出意见

你可能感兴趣的:(java,java)