doc 转html

首先引进poi的jar包 到http://poi.apache.org/download.html下载

servlet如下

package com.solaw.servlet;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
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.commons.io.output.ByteArrayOutputStream;
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.w3c.dom.Document;

import com.sun.image.codec.jpeg.ImageFormatException;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageDecoder;

public class ViewDocument extends HttpServlet {
	private static final long serialVersionUID = 1L;

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		try {
			String documentPath = (String) request.getParameter("documentPath");
			try {
				documentPath = new String(documentPath.getBytes("ISO-8859-1"),
						"utf-8");
				String inputfilepath = documentPath;
				response.setContentType("text/html");
				PrintWriter out = response.getWriter();
				// String outputfilepath=System.getProperty("user.dir") +
				// "/docs/runke.html";
				convert2Html(inputfilepath, out);
			} catch (UnsupportedEncodingException e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
			} catch (Exception e) {
				e.printStackTrace();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		response.setContentType("text/html");
		PrintWriter out = response.getWriter();
		out.println("<!DOCTYPE HTML PUBLIC -//W3C//DTD HTML 4.01 Transitional//EN>");
		out.println("<HTML>");
		out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
		out.println(" <BODY>");
		out.print(" This is ");
		out.print(this.getClass().getName());
		out.println(", using the POST method");
		out.println("your hobby is:" + request.getParameter("hobby"));
		out.println(" </BODY>");
		out.println("</HTML>");
		out.flush();
		out.close();
	}

	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));
			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) {
			}
		}
	}

	public static void convert2Html(String fileName, PrintWriter responseOut)
			throws TransformerException, IOException,
			ParserConfigurationException {
		HWPFDocument wordDocument = new HWPFDocument(new FileInputStream(
				fileName));// WordToHtmlUtils.loadDoc(new
							// FileInputStream(inputFile));
		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 "test/" + suggestedName;
			}
		});
		wordToHtmlConverter.processDocument(wordDocument);
		// save pictures
		List pics = wordDocument.getPicturesTable().getAllPictures();
		if (pics != null) {
			for (int i = 0; i < pics.size(); i++) {
				Picture pic = (Picture) pics.get(i);
				System.out.println();
				try {
					pic.writeImageContent(new FileOutputStream(System
							.getProperty("user.dir")
							+ "/docs/"
							+ 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, "ISO-8859-1");
		serializer.setOutputProperty(OutputKeys.INDENT, "yes");
		serializer.setOutputProperty(OutputKeys.METHOD, "html");
		serializer.transform(domSource, streamResult);
		out.close();
		responseOut.write(new String(out.toByteArray()));
		// writeFile(new String(out.toByteArray()), outPutFile);
	}

	// public static void convert2Html(String fileName, String outPutFile)
	// throws TransformerException, IOException,
	// ParserConfigurationException {
	// HWPFDocument wordDocument = new HWPFDocument(new
	// FileInputStream(fileName));//WordToHtmlUtils.loadDoc(new
	// FileInputStream(inputFile));
	// 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 "test/"+suggestedName;
	// }
	// } );
	// wordToHtmlConverter.processDocument(wordDocument);
	// //save pictures
	// List pics=wordDocument.getPicturesTable().getAllPictures();
	// if(pics!=null){
	// for(int i=0;i<pics.size();i++){
	// Picture pic = (Picture)pics.get(i);
	// System.out.println();
	// try {
	// pic.writeImageContent(new FileOutputStream(System.getProperty("user.dir")
	// + "/docs/"
	// + 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);
	// }
}

同时web.xml需要配置

<servlet>
		<servlet-name>ViewDocument</servlet-name>
		<servlet-class>com.solaw.servlet.ViewDocument</servlet-class>
	</servlet>
	<servlet-mapping>
		<servlet-name>ViewDocument</servlet-name>
		<url-pattern>/visitor/viewDocument</url-pattern>
	</servlet-mapping>


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值