html頁面轉換成pdf

通常頁面都是.jsp頁面,因此要把.jsp轉換成html,在生成pdf,在網上找了好多方法,只有用一個插件,wkhtmltopdf-0.8.3.exe,生成的pdf會相對的好看。javascript

先附上我作的.jsp頁面。html

<%@ page language="java" contentType="text/html;charset=utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html lang="en" id="htmlId">
<head>
     <meta charset="UTF-8" />
    <style>
        .box{
            /* width: 1000px;
            border:1px solid red; */
            text-align: center;
            
        }
        table{
            width: 100%;
        }
        table, th, td {
            border: 1px solid grey;
            border-collapse: collapse;
            font-size: 12px;
        }
        table th {
            height: 40px;
            line-height: 40px;
            background: #cdcdcd;
            text-align: center;
        }
        table td {
            height: 40px;
            line-height: 40px;
            color: black;
            text-align: center;
        }

        /*若是要隔行變色把下面解開換色就行*/
     /*   table tr:nth-child(odd) {
            background-color: white;
        }
        table tr:nth-child(even) {
            background-color:#99ccff;
        }*/
        .civilRecord{
            margin-top: 20px;
        }
        /*這是固定某一列表格的寬度*/
        .civilRecord .th1{
            width: 70px;
        }
        .civilRecord .th3{
            width: 190px;
        }
        .civilRecord .th4{
            width: 190px;
        }
        .civilRecord .th5{
            width: 190px;
        }
        .protectionin{
         margin-top: 20px;
        }
        
        .bj{
            margin-left: 5%;
            margin-right: 5%;        
        }

    </style>
    <script type="text/javascript" src="resource/jquery/jquery-1.9.1.min.js"></script>
    		<script type="text/javascript">
      function msg() {
    	  /* var url = 'assurehistory.do?reqCode=exportAssurehistoryPDF';
		  //window.location.href = url; 
		  var html=$("#htmlId").html();
		  //alert(html);
		  //return;
		  $.ajax({
	             type: "post",
	             url: url,
	             data: {htmlContent:html},
	             dataType: "json",
	             success: function(data){
	            	 //alert(data.msg);
	             }
	         }); */
	         var form=$("<form>");//定義一個form表單
	         form.attr("style","display:none");
	         form.attr("target","");
	         form.attr("method","post");
	         form.attr("action","assurehistory.do?reqCode=exportAssurehistoryPDF");
	         var input1=$("<input>");
	         input1.attr("type","hidden");
	         input1.attr("name","htmlContent");
	         var html=$("#htmlId").html();
	        // alert(html);
	         input1.attr("value",html);
	         $("#pdfBody").append(form);//將表單放置在web中
	         form.append(input1);
	         form.submit();//表單提交 
       }

</script>
</head>
<body id="pdfBody">
<div class="box" style="height:430px;overflow:auto">
    <div style="margin-left:80%;line-height: 28px;position: relative;">
    <input type="button" value="導出PDF" onclick="msg()"/>
		</div>
  <!-- <h3>三 公共信息明細</h3> -->
    <div class="taxesRecord bj">
        <p>我的擔保基礎信息</p>
        <table >
            <thead>
            <tr>
                <th>信息記錄類型</th>
                <th>帳戶類型</th>
                <th>帳戶標識碼</th>
                <th>信息報告日期</th>
            </tr>
            </thead>
            <tbody>
            <tr>
            <c:forEach var="assureinfos" items="${assureinfos}">
                <td>${assureinfos.infotypetext}</td>
                <td>${assureinfos.acctypetext}</td>
                <td>${assureinfos.acccode}</td>
                <td>${assureinfos.repdateStr}</td>
                </c:forEach>
            </tr>
            </tbody>
        </table>
        <table>
         <thead>
            <tr>
                <th>報告時點說明代碼</th>
                <th>債務人姓名</th>
                <th>債務人證件類型</th>
                <th>債務人證件號碼</th>
                <th>業務管理機構代碼</th>
            </tr>
            </thead>
            <tbody>
            <tr>
            <c:forEach var="assureinfos" items="${assureinfos}">
                <td>${assureinfos.repcodetext}</td>
                <td>${assureinfos.debtorname}</td>
                <td>${assureinfos.debtoridtypetext}</td>
                <td>${assureinfos.debtoridnum}</td>
                <td>${assureinfos.organcode}</td>
                </c:forEach>
            </tr>
            </tbody>
        </table>
    </div>
    <div class="civilRecord bj">
        <p>擔保人基本信息</p>
        <table>
            <thead>
            <tr>
                <th class="th1">擔保業務大類</th>
                <th class="th1">擔保業務種類細分</th>
                <th class="th1">開戶日期</th>
                <th class="th1">信用額度</th>
                <th class="th1">幣種</th>
            </tr>
            </thead>
            <tbody>
            <tr>
            <c:forEach var="assurebasicinfos" items="${assurebasicinfos}">
                <td>${assurebasicinfos.suretybusstext }</td>
                <td>${assurebasicinfos.suretybussspeartext}</td>
                <td>${assurebasicinfos.opendateStr }</td>
                <td>${assurebasicinfos.creditlimit }</td>
                <td>${assurebasicinfos.currencytypetext }</td>
             </c:forEach>
            </tr>
            </tbody>
        </table>
        <table>
            <thead>
            <tr>
                <th class="th1">到期日期</th>
                <th class="th1">反擔保方式</th>
                <th class="th1">其餘還款保證方式</th>
                <th class="th1">保證金百分比</th>
                <th class="th1">擔保合同文本編號</th>
            </tr>
            </thead>
            <tbody>
            <tr>
            <c:forEach var="assurebasicinfos" items="${assurebasicinfos}">
                <td>${assurebasicinfos.enddateStr }</td>
                <td>${assurebasicinfos.assuremodetext }</td>
                <td>${assurebasicinfos.otherasstext }</td>
                <td>${assurebasicinfos.marginpercent }</td>
                <td>${assurebasicinfos.assurenum }</td>
             </c:forEach>
            </tr>
            </tbody>
        </table>
    </div>
     <div class="civilRecord bj">
        <p>在保責任信息</p>
        <table>
            <thead>
            <tr>
                <th class="th1">帳戶狀態</th>
                <th class="th1">在保餘額</th>
                <th class="th1">餘額變化日期</th>
                <th class="th1">五級分類</th>
                <th class="th1">五級分類認定日期</th>
            </tr>
            </thead>
            <tbody>
            <tr>
            <c:forEach var="protectioninfos" items="${protectioninfos}">
                <td>${protectioninfos.accstatetext }</td>
                <td>${protectioninfos.protectionbal }</td>
                <td>${protectioninfos.balchangedateStr }</td>
                <td>${protectioninfos.classifytext }</td>
                <td>${protectioninfos.classifydateStr }</td>
             </c:forEach>
            </tr>
            </tbody>
        </table>
        <table>
            <thead>
            <tr>
                <th class="th1">風險敞口</th>
                <th class="th1">代償標誌</th>
                <th class="th1">帳戶關閉日期</th>
                <th class="th1"></th>
                <th class="th1"></th>
            </tr>
            </thead>
            <tbody>
            <tr>
            <c:forEach var="protectioninfos" items="${protectioninfos}">
                <td>${protectioninfos.riskexposure }</td>
                <td>${protectioninfos.compenflagtext }</td>
                <td>${protectioninfos.accclosedateStr }</td>
                <td></td>
                <td></td>
             </c:forEach>
            </tr>
            </tbody>
        </table>
    </div>
     <div class="civilRecord bj">
        <p>相關還款人信息</p>
        <table>
            <thead>
            <tr>
                <th class="th1">責任人個數</th>
                <th class="th1">身份類別</th>
                <th class="th1">責任人名稱</th>
                <th class="th1">責任人身份標識類型</th>
                <th class="th1">責任人身份標識號碼</th>
            </tr>
            </thead>
             <c:forEach var="rep" items="${repaymentinfos}">
            <tbody>
            <tr>
                <td>${rep.perliabnum}</td>
                <td>${rep.classifytypetext}</td>
                <td>${rep.perliabname}</td>
                <td>${rep.perliabtypetext}</td>
                <td>${rep.perliabid}</td>
            </tr>
            </tbody>
            </c:forEach>
        </table>
        <table>
            <thead>
            <tr>
                <th class="th1">還款責任人類型</th>
                <th class="th1">還款責任金額</th>
                <th class="th1"></th>
                <th class="th1"></th>
                <th class="th1"></th>
            </tr>
            </thead>
            <c:forEach var="rep" items="${repaymentinfos}">
            <tbody>
            <tr>
                <td>${rep.reperliabtypetext}</td>
                <td>${rep.reperliabamot}</td>
                <td></td>
                <td></td>
                <td></td>
          
            </tr>
            </tbody>
            </c:forEach>
        </table>
    </div>
     <div class="civilRecord bj">
        <p>抵押物信息</p>
        <table>
            <thead>
            <tr>
                <th class="th1">抵質押合同個數</th>
                <th class="th1">抵質押合同標識碼</th>
                <th class="th1"></th>
                <th class="th1"></th>
                <th class="th1"></th>
            </tr>
            </thead>
             <c:forEach var="contractinfos" items="${contractinfos}">
            <tbody>
            <tr>
                <td>${contractinfos.contractnum }</td>
                <td>${contractinfos.contractid }</td>
                <td></td>
                <td></td>
                <td></td>
            </tr>
            </tbody>
             </c:forEach>
        </table>
    </div>
</div>
</body>
</html>

我用el表達式動態獲得數據庫裏面的數據,而後在導出方法中,定義了from表單,把整個jsp源碼獲取到。java

頁面的效果:jquery

下面附上後臺的方法:web

import java.io.BufferedInputStream;
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.InputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.check.test.HtmlToPdf;

/** * 將html轉成pdf * @param request * @param response * @return */ @RequestMapping(params = "reqCode=exportAssurehistoryPDF") public ModelAndView exportAssurehistoryPDF(HttpServletRequest request,HttpServletResponse response){ try { request.setCharacterEncoding("UTF-8"); } catch (UnsupportedEncodingException e2) { e2.printStackTrace(); } String h = request.getParameter("htmlContent"); System.out.println(h); String pPath=this.writeHtmlToFile(h, "assurehistory"); HtmlToPdf.convert(pPath+"/assurehistory.html", pPath+"/assurehistory.pdf"); try { //Thread.sleep(1000); response.setContentType("application/pdf"); response.addHeader("content-disposition", "attachment;filename="+ URLEncoder.encode("我的擔保信息查詢統計.pdf", "UTF-8")); File file = new File(pPath+"/assurehistory.pdf"); InputStream fis = new BufferedInputStream(new FileInputStream(file)); byte[] buffer = new byte[fis.available()]; fis.read(buffer); fis.close(); OutputStream os = response.getOutputStream(); os.write(buffer); os.flush(); os.close(); } catch (UnsupportedEncodingException e1) { e1.printStackTrace(); }catch (FileNotFoundException e) { e.printStackTrace(); } catch (IOException e) { e.printStackTrace(); } return null; } /** * 將內容寫入html文件 * @param content * @param htmlName * @return */ private String writeHtmlToFile(String content,String htmlName) { String path = ""; try { path = URLDecoder.decode(AssurehistoryController.class.getClassLoader().getResource("pdfFile/").getFile(), "utf-8"); } catch (UnsupportedEncodingException e) { e.printStackTrace(); } System.out.println(path); content=content.replace("<div class=\"box\" style=\"height:430px;overflow:auto\">", "<div class=\"box\" style=\"overflow:auto\">"); content=content.replace("button", "hidden").replace("HEIGHT: 430px", ""); File file = new File(path + htmlName+".html"); BufferedWriter bw = null; try { bw = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(file),"utf-8")); bw.write("<!DOCTYPE html><html lang=\"en\">"); bw.write(content); bw.write("</html>"); bw.flush(); } catch (IOException e) { e.printStackTrace(); } finally { if (bw != null) { try { bw.close(); } catch (IOException e) { e.printStackTrace(); } } } return file.getParent(); }

 而後在定義一個HtmlToPdf類,你也能夠把這個類的方法單獨拿出來。ajax

package com.check.test;

import java.io.File;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;

import com.eloan.app.assurehistory.controller.AssurehistoryController;

public class HtmlToPdf {
    
    
    /**
     * html轉pdf
     * @param srcPath html路徑,能夠是硬盤上的路徑,也能夠是網絡路徑
     * @param destPath pdf保存路徑
     * @return 轉換成功返回true
     */
    public static boolean convert(String srcPath, String destPath){
    	//wkhtmltopdf在系統中的路徑
    	String str="";
		try {
			str = URLDecoder.decode(AssurehistoryController.class.getClassLoader().getResource("pdfFile/wkhtmltopdf-0.8.3.exe").getFile(), "utf-8");
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		String path = new File(str).getPath();
        File file = new File(destPath);
        File parent = file.getParentFile();
        //若是pdf保存路徑不存在,則建立路徑
        if(!parent.exists()){
            parent.mkdirs();
        }
        StringBuilder cmd = new StringBuilder();
        cmd.append(path);
        cmd.append(" ");
        cmd.append(srcPath);
        cmd.append(" ");
        cmd.append(destPath);
        
        boolean result = true;
        try{
            Process proc = Runtime.getRuntime().exec(cmd.toString());
            proc.waitFor();
        }catch(Exception e){
            result = false;
            e.printStackTrace();
        }
        
        return result;
    }
    
  
}

 最後,還有個重要的,就是wkhtmltopdf-0.8.3.exe,這個你們能夠在網上免費下載,我把它放在我項目的src/main/java下面數據庫

 

最後,生成的pdf效果是:json

相關文章
相關標籤/搜索