html转pdf生成

1.先生成动态html页面,当然也可以直接拿静态html页面写入。

2.再生成pdf文件,通过这个itextpdf工具jar,有个xmlWorkerhelper适配器进行组装,Document来设置页面宽高,源码默认设置是A4。


3.进行游览器下载,从后台拿到uid.pdf文件,设置文件头,及下载类型,注意乱码问题,再次删除原来意生成的pdf

/**
	 * pdf下载
	 * @param request
	 * @param response
	 * @param fileName
	 * @param year
	 */
	@RequestMapping("/downloadpdf")
	public void downloadpdf(HttpServletRequest request, HttpServletResponse response, String fileName,String year) {
		try {
			String path = request.getSession().getServletContext().getRealPath("") + "/WEB-INF/resources/pdf/out/";
			path += fileName;
			File file = new File(path);
			if (!file.exists()) {
				String errorMessage = java.net.URLEncoder.encode("文件不存在","UTF-8");
				System.out.println(errorMessage);
				OutputStream outputStream = response.getOutputStream();
				outputStream.write(errorMessage.getBytes(Charset.forName("UTF-8")));
				outputStream.close();
				return;
			}
			String mimeType = request.getSession().getServletContext().getMimeType(file.getName());
			if (mimeType == null) {
				mimeType = "application/octet-stream";
			}
			response.setContentType(mimeType);
			response.setContentLength((int) file.length());
			String yearFDFName=year+"资格确认汇总表.pdf";
			String filenameURL=new String(yearFDFName.getBytes("utf-8"),"iso8859-1");
            if(request.getHeader("user-agent").toLowerCase().contains("msie")){
        	      filenameURL=URLEncoder.encode(yearFDFName, "UTF-8");  //ie乱码问题
            }
			response.setHeader("Content-Disposition", "attachment;filename="+filenameURL);
			InputStream inputStream = new BufferedInputStream(new FileInputStream(file));
			FileCopyUtils.copy(inputStream, response.getOutputStream());
			file.delete();
		} catch (Exception e) {
			e.printStackTrace();
			LOGGER.error(e.getMessage());
		}

	}



package cn.sh.sstic.mgt.proj.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.PrintStream;
import java.util.List;
import java.util.UUID;

import com.itextpdf.text.Document;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;

import cn.sh.sstic.mgt.proj.entity.ViewInfoModel;



public class PDFNewUtil {

	/**
	 * PDF生成工具(无水印)
	 */
	public static String createPDF(final String path,List<ViewInfoModel> vm) throws Exception {
		// 输出路径
		String uuid = UUID.randomUUID().toString();
		String outFileName = path + "/out/" + uuid + ".pdf";
		String htmlFileName = path + "/template/" + uuid + ".html";
	    	try {
	    		//生成html
				createHtml(vm,htmlFileName);
				Rectangle rect =new Rectangle(1120,600);
				Document document = new Document(rect);
				//生成pdf
				PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(outFileName));
				document.open();
				//合并
				XMLWorkerHelper.getInstance().parseXHtml(writer, document, new FileInputStream(htmlFileName)/*,Charset.forName("UTF-8")*/);
				document.close();
			} catch (Exception e) {
				System.out.println(e.getMessage());
			}
		    File file = new File(htmlFileName);
			if(file.exists()){
				file.delete();
			}
		return uuid + ".pdf";
	 }
	
	   
	    /**
	     * 动态生成html
	     * @param list
	     * @param htmlFileName
	     */
		public static void createHtml(List<ViewInfoModel> list,String htmlFileName){
			StringBuilder stringHtml = new StringBuilder();  
			try {
				PrintStream printStream = new PrintStream(new FileOutputStream(htmlFileName));
				//输入HTML文件内容  
				stringHtml.append("<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\"  \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">");
				stringHtml.append("<html><head>");  
				stringHtml.append("<meta http-equiv=\"Content-Type\" content=\"text/html;charset=UTF-8\"/>");  
				stringHtml.append("</head>");  
				stringHtml.append("<body>");
				stringHtml.append("<h2 style=\"font-family: 宋体; text-align:center;\">国家大学科技园免税确认表</h2>");
				stringHtml.append("<div><table border=\"1\" cellspacing=\"0\" cellpadding=\"1\" style=\"text-align:center;font-size:20px;margin:auto;width:100%\">");  
				stringHtml.append("<tr style=\"font-family: 宋体;height:50px\">");
				stringHtml.append("<td style=\"width:10%\">  序号  </td><td style=\"width:\">单位名称</td><td style=\"width:\">科技园孵化场地地址和范围</td>");
			    stringHtml.append("<td style=\"width:\">财务是否独立核算</td><td style=\"width:\">孵化器场地面积占比(%)</td><td style=\"width:\">孵化企业数量占比(%) </td>");
			    stringHtml.append("</tr>");
			    if(list.size()>0 || list!=null){ 
			    	for(int i=0;i<list.size();i++){  
			    		ViewInfoModel obj= list.get(i);
			    		stringHtml.append("<tr style=\"font-family: 宋体;height:50px\">");
			    		stringHtml.append("<td style=\"width:10%\">"+(i+1)+"</td>");
			    		stringHtml.append("<td style=\"width:\">"+(obj.getComName()==null?"":obj.getComName())+"</td>");
			    		stringHtml.append("<td style=\"text-align:left;width:\">"+(obj.getCdhfw()==null?"":obj.getCdhfw())+"</td>");
			    		stringHtml.append("<td style=\"width:\">"+(obj.getSfddhs()==null?"":obj.getSfddhs())+"</td>");
			    		stringHtml.append("<td style=\"width:\">"+(obj.getFhcdmj()==null?"":obj.getFhcdmj())+"</td>");
			    		stringHtml.append("<td style=\"width:\">"+(obj.getFhqysl()==null?"":obj.getFhqysl())+"</td>");
			    		stringHtml.append("</tr>");
			    	}
			    }
				stringHtml.append("</table>"); 
				stringHtml.append("<p style=\"font-family: 宋体;font-size:20px;\">省级科技主管部门盖章:                  省级教育主管部门盖章      </p>");
				stringHtml.append("<br></br>");
				stringHtml.append("<p style=\"font-family: 宋体;text-align: right;font-size:20px;\">  2017年  月  日    </p>");
				stringHtml.append("<span style=\"font-family: 宋体;font-size:20px\">注:</span>");
				stringHtml.append("<ol style=\"font-size:22px;\">");
				stringHtml.append("<li style=\"font-family: 宋体;list-style-position: inside;\">数据申报时点为2016年12月31日;</li>");
				stringHtml.append("<li style=\"font-family: 宋体;list-style-position: inside;\">孵化场地面积占比=(在孵企业使用面积+公共服务面积)/ 园区场地总面积,孵化企业数量占比=在孵企业总数 / 园区内企业总数;</li>");
				stringHtml.append("<li style=\"font-family: 宋体;list-style-position: inside;\">本表中“在孵企业”、“公共服务面积”等指标定义遵照《关于国家大学科技园税收政策的通知》财税〔2016〕98号文件相关要求;单位名称以科技部、教育部确认国家大学科技园认定名称为准;</li>");
				stringHtml.append("<li style=\"font-family: 宋体;list-style-position: inside;\">表格不足可自行添加;</li>");
				stringHtml.append("<li style=\"font-family: 宋体;list-style-position: inside;\">省级科技主管部门、省级教育主管部门汇总确认后加盖公章。</li></ol>");
				stringHtml.append("</div></body></html>"); 
				printStream.println(stringHtml.toString());  
			} catch (Exception e) {
			    System.out.println(e.getMessage());
			}
		}
	
}





  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值