天天看點

java用HTML加載動态資料生成PDF下載下傳(demo含jar)

最近工作需要,項目中部分頁面需要轉化成pdf進行下載下傳,我們的頁面用的是jsp,但是jsp不能直接轉pdf,需要用html,是以部分頁面又重做了一份,做成了html樣式,因為這個東西用的不多,太深的東西沒有去看,此處僅給出html轉pdf的demo,讓你拿到即可用,heml需要用ajax動态渲染資料,我這裡寫的是靜态的資料。

代碼是我從網上找的,然後自己補充了部分jar和類的引用等東西,拿到即可用

所需的jar包

jar包引入這一個就行,會關聯下載下傳别的
        <dependency>
            <groupId>org.xhtmlrenderer</groupId>
            <artifactId>core-renderer</artifactId>
            <version>R8</version>
        </dependency>
           

pdf做文字文字轉化的時候需要用到字型,這裡用的是 simsun.ttc

下載下傳路徑是

http://www.font5.com.cn/font_download.php?id=&part=
           

下載下傳後在檔案的位置是

java用HTML加載動态資料生成PDF下載下傳(demo含jar)

PdfUtil.java

package com.jp.controller;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.HttpURLConnection;
import java.net.URL;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.w3c.dom.Document;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer;

//import com.itextpdf.text.pdf.BaseFont;
import com.lowagie.text.pdf.BaseFont;

@Controller
@RequestMapping("/ces")
public class PdfUtil {

    @RequestMapping("/ces.do")
    public void cess() throws Exception{
        System.out.println("開始了=====");
        htmlToPdf2("d:/pdf/11111.pdf","http://127.0.0.1:8080/shopuu_mvc/ces/ce.do");
        System.out.println("結束了=====");
    }

        @RequestMapping("/ce.do")
    public ModelAndView ces(){
        Map<String, Object> map =new HashMap<String, Object>();
        map.put("payResponse", "ljp");
        map.put("op_date", new Date());
    //request.setAttribute("option", "pdf  download");
        return new ModelAndView("first", map);
    }


    /**
     * 把URL轉換為PDF
     * @return
     * @throws Exception
     */
    public static boolean htmlToPdf2(String outputFile, String url)
            throws Exception {
        File outFile = new File(outputFile);
        if (!outFile.exists()) {
            outFile.getParentFile().mkdirs();
        }
        OutputStream os = new FileOutputStream(outputFile);
        ITextRenderer renderer = new ITextRenderer();
        renderer.setDocument(url);
        String fontPath="/simsun.ttc";
        // 解決中文支援問題
        ITextFontResolver fontResolver = renderer.getFontResolver();
        fontResolver.addFont(fontPath, BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);
        renderer.layout();
        renderer.createPDF(os);
        os.flush();
        os.close();
        System.out.println("檔案轉換成功");
        return true;
    }

}
           

在上述 java裡面 我通路的是 http://127.0.0.1:8081/ljp_mvc/first.jsp 實際裡面寫的是html标簽

first.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isELIgnored="false"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt" %>
<html>
<head>
<title>頁面列印</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<style type='text/css'>
.tab td {
    border-bottom:  solid #000000;
    border-left:  solid #000000;
    border-right:  solid #ffffff;
    border-top:  solid #ffffff;
}

.tab {
    border-color: #000000 #000000 #000000 #000000;
    border-style: solid;
    border-top-width: px;
    border-right-width: px;
    border-bottom-width: px;
    border-left-width: px;
}

.hr {
    font-family: '宋體';
    font-size: pt;
}
</style>
</head>
 <body bgcolor='white' style='font-family:SimSun; height:100%;' screen_capture_injected='true' ryt11773='1'> 

    <table cellspacing='0' cellpadding='0' width='100%' align='center'>
        <tr>
            <td align='center' colspan='4' style='font-size: 24px'><b
                id='pdf_text'>授信曆史資訊下載下傳</b></td>
        </tr>
    </table>        


    <table class='tab' cellSpacing='0' cellPadding='0' width='100%' border='1'>
        <tr align='center' height='23'>
            <td width='10%' height='23'>姓名</td>
            <td width='10%' height='23'>${payResponse}</td>
            <td width='10%' height='23'>身份證号</td>
            <td width='10%' height='23'>${payResponse}</td>
        </tr>
        <tr align='center' height='23'>
            <td width='10%' height='23'>授信人</td>
            <td width='10%' height='23'>${payResponse}</td>
            <td width='10%' height='23'>授信日期</td>
            <td width='10%' height='23'><fmt:formatDate value="${op_date}" pattern="yyyy-MM-dd HH:mm:ss"/></td>
        </tr>
    </table>

</body>
</html> 
           

這個頁面不在 mvc項目映射的view路徑下面,first.jsp 在webapp下,個web-inf同級

繼續閱讀