标签:style class blog code java http
根据html内容生成word,并自动下载下来。使用到了itext-1.4.6.jar
import java.io.File; import java.io.FileInputStream; import java.io.FileOutputStream; import java.io.InputStream; import java.io.OutputStream; import java.io.StringReader; import java.net.URLEncoder; import java.util.List; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.util.HtmlUtils; import com.lowagie.text.Document; import com.lowagie.text.PageSize; import com.lowagie.text.Paragraph; import com.lowagie.text.html.simpleparser.HTMLWorker; import com.lowagie.text.html.simpleparser.StyleSheet; import com.lowagie.text.rtf.RtfWriter2; import com.rimi.common.util.Common; public class MSOfficeGeneratorUtils { public static void htmlToWord(HttpServletRequest request,HttpServletResponse response,String s){ try { String docUrl=request.getSession().getServletContext().getRealPath("")+File.separator+"fileUpload"+File.separator; docUrl+=Common.getUUID()+".doc"; OutputStream out = new FileOutputStream(docUrl); Document document = new Document(PageSize.A4); RtfWriter2.getInstance(document, out); document.open(); Paragraph context = new Paragraph(); //String value = HtmlUtils.htmlEscape(s); //System.out.println(s); // Image img = Image.getInstance("D:\\图片\\2.jpg"); // img.setAbsolutePosition(0, 0);// // document.add(img); StyleSheet ss = new StyleSheet(); List htmlList = HTMLWorker.parseToList(new StringReader(s), ss); for (int i = 0; i < htmlList.size(); i++) { com.lowagie.text.Element e = (com.lowagie.text.Element) htmlList .get(i); context.add(e); } document.add(context); document.close(); out.close(); InputStream inStream = new FileInputStream(docUrl); response.reset(); response.setContentType("bin"); response.addHeader( "Content-Disposition", "attachment; filename=\"" + URLEncoder.encode("试题文档.doc", "UTF-8") + "\""); // 循环取出流中的数据 byte[] b = new byte[512]; int len; response.getOutputStream().flush(); while ((len = inStream.read(b)) > 0) { response.getOutputStream().write(b, 0, len); } inStream.close(); //System.out.println("ok"); } catch (Exception e) { e.printStackTrace(); } } }
根据html生成Word文件,包含图片,布布扣,bubuko.com
标签:style class blog code java http
原文地址:http://www.cnblogs.com/libaoting/p/itext.html