首页 > 代码库 > 根据html生成Word文件,包含图片
根据html生成Word文件,包含图片
根据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 = http://www.mamicode.com/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(); } }}
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。