java根据模板导出PDF详细教程(包含统计图)

本文介绍如何使用Java结合iText、FreeMarker及JFreeChart生成动态配置的PDF文档,包括中文支持、图表生成等内容。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题记:由于业务的需要,需要根据模板定制pdf文档,经测试根据模板导出word成功了;但是导出pdf相对麻烦了一点。两天的研究测试java导出PDF,终于成功了,期间走了不少弯路,今分享出来,欢迎大家有问题在此交流,与君共勉!

项目:项目下载地址

一、需求

根据业务需要,需要在服务器端生成可动态配置的PDF文档,方便数据可视化查看。

此文的测试是在客户端通过java程序的测试,直接运行java类获得成功!


二、解决方案

iText+FreeMarker+JFreeChart生成可动态配置的PDF文档。
iText有很强大的PDF处理能力,但是样式和排版不好控制,直接写PDF文档,数据的动态渲染很麻烦。
FreeMarker能配置动态的html模板,正好解决了样式、动态渲染和排版问题。
JFreeChart有这方便的画图API,能画出简单的折线、柱状和饼图,基本能满足需要。


三、实现功能

1、能动态配置PDF文档内容
2、能动态配置中文字体显示
3、能动态生成业务图片

四、关键代码说明 

1:模板配置

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

    <meta http-equiv="Content-Style-Type" content="text/css"/>
    <style type="text/css">
	<!--配置显示中文-->
        body {
            font-family: SimSun;
        }
        .center{
            text-align: center;
            width: 100%;
        }
   table{border-collapse:collapse;border-spacing:0;border:0;border-style:solid;}
   tbody td{border-style:solid;border-right-width:.5pt solid #000;border-bottom-width:.5pt solid #000;text-align: center;font-size:7pt;}
   .leftTd{border-left-width-width:.5pt solid #000;}
   .topTd{border-top-width-width:.5pt solid #000;}
   #myTable .widthCss1{width:5%;}
   #myTable .widthCss2{width:25%;}
   #myTable .widthCss3{width:15%;}
   #myTable .widthCss4{width:15%;}
   #myTable .widthCss5{width:15%;}
   #myTable .widthCss6{width:25%;}

    </style>

</head>
<body>
<!--第一页开始-->
<div class="page" >
    <div class="center" style="background-color:red;width:400px;height:100px"><p>${templateName}</p></div>
    <div><p>iText官网:${ITEXTUrl}</p></div>
    <div><p>FreeMarker官网:${freeMarkerUrl}</p></div>
    <div><p>JFreeChart教程:${JFreeChartUrl}</p></div>
	
<table  width="100%" id="myTable" >
<tbody>
 <tr>
  <td style='border-left-width-width:.5pt solid #000;border-top-width-width:.5pt solid #000;height:21.0pt;width:5%;'>序号</td>
  <td  style='border-left-width:none;border-top-width-width:.5pt solid #000;width:10%;' >xx</td>、
  <td  style='border-left-width:none;border-top-width-width:.5pt solid #000;width:15%;' >xx</td>
  <td  style='border-left-width:none;border-top-width-width:.5pt solid #000;width:15%;' >xx</td>
  <td style='border-left-width:none;border-top-width-width:.5pt solid #000;width:15%;' >xx</td>
  <td style='border-left-width:none;border-top-width-width:.5pt solid #000;width:15%;' >xx</td>
  <td style='border-left-width:none;border-top-width-width:.5pt solid #000;width:25%;' >xx</td>
 </tr>
 <tr>
  <td height=28   style='border-top-width:none;height:21.0pt;' class="leftTd widthCss1">1</td>
  <td colspan=2   style='border-left-width:none;border-top-width-width:none;' class="widthCss2">一、课桌椅(单人套)</td>
  <td  style='border-left-width:none;border-top-width-width:none;' class="widthCss3">xx</td>
  <td  style='border-left-width:none;border-top-width-width:none;' class="widthCss4">xx</td>
  <td  style='border-left-width:none;border-top-width-width:none;' class="widthCss5">xx</td>
  <td  style='border-left-width:none;border-top-width-width:none;' class="widthCss6">xx</td>
 </tr>
</tbody>
</table>

	    <!--外部链接-->
	<h3 class="text-center">这是用户的信息页!</h3>
    <div >
                <div>用户名
                密码
                年龄
                地址</div>
			  <#list userList as user>
						<div>${user.username}
						${user.password}
						${user.age}
						${user.address}</div>
					<hr/>
		</#list>
    </div>
    <!--外部链接-->
    <p>静态logo图</p>
    <div>
        <img src="${imageUrl}" alt="美团点评" width="512" height="359"/>
    </div>
    <!--动态生成的图片-->
    <p>气温变化对比图</p>
    <div>
        <img src="${picUrl}" alt="我的图片" width="500" height="270"/>
    </div>
</div>
<!--第一页结束-->
<!---分页标记-->
<span style="page-break-after:always;"></span>
<!--第二页开始-->
<div class="page">
    <div>第二页开始了</div>
    <div>列表值:</div>
    <div>
    <#list scores as item>
        <div><p>${item}</p></div>
    </#list>
    </div>

</div>
<!--第二页结束-->
</body>
</html>

2:主要实现类

package main.java.pdf.kit.component;

import com.itextpdf.text.Document;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import freemarker.cache.StringTemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;
import main.java.pdf.kit.exception.PDFException;
import java.io.*;
import java.nio.charset.Charset;


public class PDFKit {

    private String saveFilePath;
    public static final String FILE_PATH ="e:/html/result.html";//文件指定存放的路径
    
  
    /*
    * 把模板读入到String中,然后根据String构造FreeMarker模板
    */
   public  void createHtmlFromString(Object data) {
       BufferedInputStream in = null;
       FileWriter out = null;
       try {
           //模板文件
           File file = new File("E:\\html\\hello.ftl");
           //构造输入流
           in = new BufferedInputStream(new FileInputStream(file));
           int len;
           byte[] bytes = new byte[1024];
           //模板内容
           StringBuilder content = new StringBuilder();
           while((len = in.read(bytes)) != -1) {
               content.append(new String(bytes, 0, len, "utf-8"));
           }
           
           //构造Configuration
           Configuration configuration = new Configuration();
           //构造StringTemplateLoader
           StringTemplateLoader loader = new StringTemplateLoader();
           //添加String模板
           loader.putTemplate("test", content.toString());
           //把StringTemplateLoader添加到Configuration中
           configuration.setTemplateLoader(loader);     
           //构造Model
           //获取模板
           Template template = configuration.getTemplate("test");
           //生成html
           File dirPath = new File(FILE_PATH);
           if(!dirPath.getParentFile().exists()){
        	   dirPath.getParentFile().mkdirs();
           }
           //构造输出路
           out = new FileWriter(FILE_PATH);
           //生成HTML
			template.process(data, out);
       } catch (TemplateException e) {
   			e.printStackTrace();
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       } catch (UnsupportedEncodingException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       } finally {
           if(null != in) {
               try {
                   in.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
           if(null != out) {
               try {
                   out.close();
               } catch (IOException e) {
                   e.printStackTrace();
               }
           }
       }
       
   }
    /**
     * @description     导出pdf到文件
     * @param fileName  输出PDF文件名
     * @param data      模板所需要的数据
     *
     */
    public String exportToFile(String fileName,Object data){
    	try {
    		//根据模板生成html
    		createHtmlFromString( data);
            File file=new File(saveFilePath);
            if(!file.getParentFile().exists()){
                file.getParentFile().mkdirs();
            }
            Document document =null;
            try{
            	 // step 1
               document = new Document();
                // step 2
                PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
                // step 3
                document.open();
                // step 4
                XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                        new FileInputStream(FILE_PATH),  Charset.forName("UTF-8")
                       );
                System.out.println("生成完成");
            }catch(Exception ex){
                throw new PDFException("PDF export to File fail",ex);
            }finally{
            	 document.close();
            }
            
		} catch (Exception e) {
			e.printStackTrace();
		}
    	return saveFilePath;
    }
    public String getSaveFilePath() {
        return saveFilePath;
    }
    public void setSaveFilePath(String saveFilePath) {
        this.saveFilePath = saveFilePath;
    }

}

3:测试类

package test.java.pdf.kit;




import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.pdf.PdfWriter;
import com.itextpdf.tool.xml.XMLWorkerHelper;
import main.java.pdf.kit.component.PDFKit;
import main.java.pdf.kit.component.chart.Line;
import main.java.pdf.kit.component.chart.impl.DefaultLineChart;

import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by fgm on 2017/4/17.
 * 360报告
 *
 */
public class ReportKit360 {
	
	
    public static final String HTML = "E:index.html";
    public static final String DEST = "E:hello.pdf";
 
    /**
     * Creates a PDF with the words "Hello World"
     * @param file
     * @throws IOException
     * @throws DocumentException
     */
    public static void createPdf(String file) throws IOException, DocumentException {
        // step 1
        Document document = new Document();
        // step 2
        PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(file));
        // step 3
        document.open();
        // step 4
        XMLWorkerHelper.getInstance().parseXHtml(writer, document,
                new FileInputStream(HTML), Charset.forName("UTF-8"));
        System.out.println("生成完成");
        // step 5
        document.close();
    }
    /**
     * Creates a PDF with the words "Hello World"
     * @param file
     * @throws IOException
     * @throws DocumentException
     */
    public static void createPdf2() throws IOException, DocumentException {
    	 ReportKit360 kit=new ReportKit360();
         //数据
         TemplateBO templateBO=new TemplateBO();
         templateBO.setTemplateName("测试");
         templateBO.setFreeMarkerUrl("http://www.zheng-hang.com/chm/freemarker2_3_24/ref_directive_if.html");
         templateBO.setITEXTUrl("http://developers.itextpdf.com/examples-itext5");
         templateBO.setJFreeChartUrl("http://www.yiibai.com/jfreechart/jfreechart_referenced_apis.html");
         templateBO.setImageUrl("E:/3.png");
         List<String> scores=new ArrayList<String>();
         scores.add("94");
         scores.add("95");
         scores.add("98");
         templateBO.setScores(scores);
         List<Map<String,String>> userList=new ArrayList<Map<String,String>>();
         Map<String,String> userMap1=new HashMap<String,String>();
         userMap1.put("username", "张三");
         userMap1.put("password", "123456");
         userMap1.put("age", "12");
         userMap1.put("address", "北京");
         userList.add(userMap1);
         Map<String,String> userMap2=new HashMap<String,String>();
         userMap2.put("username", "张三");
         userMap2.put("password", "123456");
         userMap2.put("age", "12");
         userMap2.put("address", "北京");
         userList.add(userMap2);
         templateBO.setUserList(userList);
         //折线图数据
         List<Line> lineList=getTemperatureLineList();
         DefaultLineChart lineChart=new DefaultLineChart();
         lineChart.setHeight(400);
         lineChart.setWidth(600);
         lineChart.setFileName("折现图");;
       //折线图图片地址
         String picUrl=lineChart.draw(lineList,0);
         
         templateBO.setPicUrl(picUrl);
         System.out.println("picUrl:"+picUrl);
         String path= kit.createPDF(templateBO,"hello.pdf");
         System.out.println("打印:"+path);
    }

    public static List<Line> getTemperatureLineList() {
        List<Line> list= new ArrayList<Line>();
        for(int i=1;i<=7;i++){
            Line line=new Line();
            float random=Math.round(Math.random()*10);
            line.setxValue("星期"+i);
            line.setyValue(20+random);
            line.setGroupName("下周");
            list.add(line);
        }
        for(int i=1;i<=7;i++){
            Line line=new Line();
            float random=Math.round(Math.random()*10);
            line.setxValue("星期"+i);
            line.setyValue(20+random);
            line.setGroupName("这周");
            list.add(line);
        }
        return list;
    }
	public  String createPDF(Object data, String fileName){
        //pdf保存路径
        try {
            PDFKit kit=new PDFKit();
            //设置输出路径
            kit.setSaveFilePath("e:/hello.pdf");
            String saveFilePath=kit.exportToFile(fileName,data);
            return  saveFilePath;
        } catch (Exception e) {
        	System.out.println("竟然失败了,艹!");
        	e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) throws IOException, DocumentException {
   /* 	File file = new File(DEST);
          file.getParentFile().mkdirs();
         createPdf(DEST);*/
         createPdf2();
      
    }
 
}
此测试工具类中,要注意几点:

        1)templateBO.setImageUrl("E:/3.png")中的参数修改为自己本地有的图片;

         2)程序可能会报找不到模板引擎hello.ftl文件的错误,一定要将源码中的hello.ftl放在本地硬盘对应的目录中;

五:生成效果图




评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值