PDF格式报表生成 (IText技术)

1. IText基本介绍

在这里插入图片描述

官网: http://itextpdf.com/ 最新iText7 涉及商业收费

在这里插入图片描述

导入iText报表jar

<dependency>
   <groupId>com.lowagie</groupId>
   <artifactId>itext</artifactId>
   <version>4.2.1</version>
</dependency>
<dependency>
   <groupId>com.itextpdf</groupId>
   <artifactId>itext-asian</artifactId>
   <version>5.2.0</version>
</dependency>
new 5.x+
<dependency>
   <groupId>com.itextpdf</groupId>
   <artifactId>itextpdf</artifactId>
   <version>5.5.9</version>
</dependency>
<dependency>
   <groupId>com.itextpdf</groupId>
   <artifactId>itext-asian</artifactId>
   <version>5.2.0</version>
</dependency>

1.2 IText基础使用

参考书籍:《[iText实战(第2版)].(iText.in.Action).Bruno.Lowagie.文字版.pdf》,在ReportAction 添加 exportPdf 方法
生成PDF五步
在这里插入图片描述

生成步骤:

1 创建Document文档
2 创建输出位置
3 打开文档
4 写入内容
5 关闭文档

package com.czxy.itext;

import com.itextpdf.awt.AsianFontMapper;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * @author Fang
 * @create 2018-10-12 21:50
 * @desc
 **/

public class TestItext {

public static void main(String[] args) throws Exception{
        // 创建一个文档
        Document document = new Document();
        // 设置输出位置
        PdfWriter.getInstance(document,new FileOutputStream(new File("d:\\a.pdf")));
        // 打开文档
        document.open();
        // 写入内容
        document.add(new Paragraph("czdx,一统江湖,千秋万代"));
        // 关闭文档
        document.close();
    }
  }

这里注意:中文是无法生成到pdf的
需要设置字体(设置可以支持中文的字库 【操作系统】 , 【导入itext-asian的jar包】)
坐标:

<dependency>
  <groupId>com.itextpdf</groupId>
  <artifactId>itext-asian</artifactId>
  <version>5.2.0</version>
</dependency>
package com.czxy.itext;

import com.itextpdf.awt.AsianFontMapper;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;


/**
 * @author Fang
 * @create 2018-10-12 21:50
 * @desc
 **/

public class TestItext {

public static void main(String[] args) throws Exception {
        //2 创建pdf对象
        Document document = new Document();
        //3 设置输出位置
        // 第一个参数:文档对象
        // 第二个参数:输出位置
        PdfWriter.getInstance(document,new FileOutputStream(new File("d:\\a.pdf")));
        //4 打开文档
        document.open();
        //5 写入内容
        // 创建BaseFont 基础字体对象
        // String name, 字体名字:宋体,楷体,隶书  AsianFontMapper.ChineseSimplifiedFont  : STSong-Light
        // String encoding:编码  +  布局方式
        // boolean embedded:是否内嵌字体   true 导出的时候将字体一并导出去       false 不导出字体
        BaseFont baseFont = BaseFont.createFont(AsianFontMapper.ChineseSimplifiedFont, AsianFontMapper.ChineseSimplifiedEncoding_H, false);

        //BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", false);


        // 通过基础字体创建字体
        /**
         * 第一个参数:baseFont
         * 第二个参数:字体大小
         *   3      :字体样式  加粗   切斜    加粗倾斜   正常.....
         *   4      :字体颜色
         */
        Font font = new Font(baseFont,16,Font.BOLDITALIC,BaseColor.BLUE);


        document.add(new Paragraph("czdx,一统江湖,千秋万代,yi  tong   jiang   hu",font));
        //6 关闭文档
        document.close();

    }
  }  

阅读:
中文的输出是Java本身的问题,为了解决中文的输出问题,需要多下载一个名为iTextAsian.jar的类库文件。该文件的下载地址为“http://prdownloads.sourceforge.net/itext/iText Asian.jar”。这个类库文件定义了与中文输出相关的一些文件。
为了输出中文,可以通过以下代码进行解决:
BaseFont bfChinese = BaseFont.createFont(“STSong-Light”, “UniGB-UCS2-H”, BaseFont.NOT_EMBEDDED);
在上述代码中,定义了中文的基础字体。其中,“STSong-Light”定义了使用的中文字体,iTextAsian.jar类库中提供了几个可供使用的字体,都是以properties结尾的文件。“UniGB-UCS2-H”定义文字的编码标准和样式,GB代表编码方式为gb2312,H代表横排字,V代表竖排字,iTextAsian.jar类库中以cmap结尾的几个文件都是关于编码和样式定义的。

1.3 IText进阶使用

在这里插入图片描述

code:


package com.czxy.bos.itextpdf;

import com.itextpdf.awt.AsianFontMapper;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

public class ITextTest03 {

    public static void main(String[] args) throws Exception{
        // 准备数据
        List<Object[]> list = new ArrayList<>();
        list.add(new Object[]{"月份","去年销量","今年销量"});
        list.add(new Object[]{"七月份",1000,1500});
        list.add(new Object[]{"八月份",1200,1300});
        list.add(new Object[]{"九月份",900,1100});


        //1 创建文档对象
        Document document = new Document();
        //2 设置输出位置
        PdfWriter.getInstance(document,new FileOutputStream(new File("d:\\出货表.pdf")));
        //3 打开文档
        document.open();
        //4 输出内容
        // 创建基础字体支持中文
        BaseFont baseFont = BaseFont.createFont(AsianFontMapper.ChineseSimplifiedFont, AsianFontMapper.ChineseSimplifiedEncoding_H, false);

        /****大标题输出******/
        Font titleFont = new Font(baseFont, 30, Font.BOLD, BaseColor.RED);
        // 居中
        Paragraph bigTitleParagraph = new Paragraph("出货表", titleFont);
        bigTitleParagraph.setAlignment(Paragraph.ALIGN_CENTER);

        document.add(bigTitleParagraph);

        /****作者输出******/
        Font authorFont = new Font(baseFont, 15, Font.NORMAL, BaseColor.BLACK);
        Paragraph authorParagraph = new Paragraph("传智学院", authorFont);
        authorParagraph.setAlignment(Paragraph.ALIGN_RIGHT);

        document.add(authorParagraph);

        /****表格输出******/
        Font contentFont = new Font(baseFont, 15, Font.NORMAL, BaseColor.BLUE);
        // 参数:列数
        PdfPTable table = new PdfPTable(3);
        // 循环数据
        for(Object[] values:list){
            table.addCell(new PdfPCell(new Phrase(values[0].toString(),contentFont)));
            table.addCell(new PdfPCell(new Phrase(values[1].toString(),contentFont)));
            table.addCell(new PdfPCell(new Phrase(values[2].toString(),contentFont)));
        }

        // 设置元素距离上一个元素的距离
        table.setSpacingBefore(10);

        // 将表格添加到文档中
        document.add(table);

        //5 关闭文档
        document.close();
    }

}

1.4 IText整合项目

在这里插入图片描述
1、在页面 waybill_manage.html 提供 pdf导出按钮

<a id="exportPdfBtn" icon="icon-print" href="#" class="easyui-linkbutton" plain="true">导出PDF报表</a>	

添加JS提交的按钮
// 导出 PDF 按钮

$("#exportPdfBtn").click(function(){
    // 下载效果 
    // $("#searchForm").attr("action", "/report/exportPdf.html");
    // $("#searchForm").submit();
    location.href="/pdf/exportPdf";
});

2、在PDFController中添加exportPdf的方法
为什么此处需要创建PDFController?
答:如果写在RepostController中的话,POI的包和IText的包冲突

package com.czxy.bos.controller.print;

import com.czxy.bos.domain.take_delivery.WayBill;
import com.czxy.bos.service.take_delivery.WayBillService;
import com.czxy.bos.util.DownloadUtil;
import com.itextpdf.awt.AsianFontMapper;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.Font;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;


import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.util.List;

@RestController
@RequestMapping("/pdf")
public class PDFController {
    @Autowired
    private WayBillService wayBillService;

    @GetMapping("/exportPdf")
    public void exportPdf(HttpServletResponse response) throws  Exception{

        //1 查找数据
        List<WayBill> wayBillList = wayBillService.findAllWayBill();

        //2 创建document文档
        Document document = new Document();
        // 创建流
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

        //3 设置输出位置--将document写进流
        PdfWriter.getInstance(document,byteArrayOutputStream);
        //4 打开文档
        document.open();
        //5 写入内容
        BaseFont baseFont = BaseFont.createFont(AsianFontMapper.ChineseSimplifiedFont, AsianFontMapper.ChineseSimplifiedEncoding_H, false);

        /****************/
        Font titleFont = new Font(baseFont, 12, Font.BOLD, BaseColor.BLACK);
        // 创建表格
        PdfPTable table = new PdfPTable(9);


        String[] titles={"编号id","运单编号","订单编号","寄件人姓名","寄件人电话","寄件人地址","收件人姓名","收件人电话","收件人地址"};
        for (String title:titles){
            table.addCell(new PdfPCell(new Phrase(title,titleFont)));
        }

        for (WayBill wayBill:wayBillList){
            table.addCell(new PdfPCell(new Phrase(wayBill.getId()+"",titleFont)));
            table.addCell(new PdfPCell(new Phrase(wayBill.getWayBillNum(),titleFont)));
            table.addCell(new PdfPCell(new Phrase(wayBill.getOrderId()+"",titleFont)));
            table.addCell(new PdfPCell(new Phrase(wayBill.getSendName(),titleFont)));
            table.addCell(new PdfPCell(new Phrase(wayBill.getSendMobile(),titleFont)));
            table.addCell(new PdfPCell(new Phrase(wayBill.getSendAddress(),titleFont)));
            table.addCell(new PdfPCell(new Phrase(wayBill.getRecName(),titleFont)));
            table.addCell(new PdfPCell(new Phrase(wayBill.getRecMobile(),titleFont)));
            table.addCell(new PdfPCell(new Phrase(wayBill.getRecAddress(),titleFont)));
        }
        // 将表格写进文档中
        document.add(table);

        //6 关闭文档
        document.close();

        //7 下载
        DownloadUtil downloadUtil = new DownloadUtil();

        downloadUtil.download(byteArrayOutputStream,response,"报表.pdf");

    }

DownloadUtil.java

package com.czxy.bos.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;

public class DownloadUtil {
	
	/**
	 * @param filePath 要下载的文件路径
	 * @param returnName 返回的文件名
	 * @param response HttpServletResponse
	 * @param delFlag 是否删除文件
	 */
	protected void download(String filePath,String returnName,HttpServletResponse response,boolean delFlag){
		this.prototypeDownload(new File(filePath), returnName, response, delFlag);
	}


	/**
	 * @param file 要下载的文件
	 * @param returnName 返回的文件名
	 * @param response HttpServletResponse
	 * @param delFlag 是否删除文件
	 */
	protected void download(File file,String returnName,HttpServletResponse response,boolean delFlag){
		this.prototypeDownload(file, returnName, response, delFlag);
	}
	
	/**
	 * @param file 要下载的文件
	 * @param returnName 返回的文件名
	 * @param response HttpServletResponse
	 * @param delFlag 是否删除文件
	 */
	public void prototypeDownload(File file,String returnName,HttpServletResponse response,boolean delFlag){
		// 下载文件
		FileInputStream inputStream = null;
		ServletOutputStream outputStream = null;
		try {
			if(!file.exists()) return;
			response.reset();
			//设置响应类型	PDF文件为"application/pdf",WORD文件为:"application/msword", EXCEL文件为:"application/vnd.ms-excel"。  
			response.setContentType("application/octet-stream;charset=utf-8");

			//设置响应的文件名称,并转换成中文编码
			//returnName = URLEncoder.encode(returnName,"UTF-8");
			returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1"));	//保存的文件名,必须和页面编码一致,否则乱码
			
			//attachment作为附件下载;inline客户端机器有安装匹配程序,则直接打开;注意改变配置,清除缓存,否则可能不能看到效果
			response.addHeader("Content-Disposition",   "attachment;filename="+returnName);  
			
			//将文件读入响应流
			inputStream = new FileInputStream(file);
			outputStream = response.getOutputStream();
			int length = 1024;
			int readLength=0;
			byte buf[] = new byte[1024];
			readLength = inputStream.read(buf, 0, length);
			while (readLength != -1) {
				outputStream.write(buf, 0, readLength);
				readLength = inputStream.read(buf, 0, length);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				outputStream.flush();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				outputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				inputStream.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			//删除原文件
			
			if(delFlag) {				
				file.delete();
			}
		}
	}

	/**
	 * by tony 2013-10-17
	 * @param byteArrayOutputStream 将文件内容写入ByteArrayOutputStream
	 * @param response HttpServletResponse	写入response
	 * @param returnName 返回的文件名
	 */
	public void download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String returnName) throws IOException{
		response.setContentType("application/octet-stream;charset=utf-8");
		returnName = response.encodeURL(new String(returnName.getBytes(),"iso8859-1"));			//保存的文件名,必须和页面编码一致,否则乱码
		response.addHeader("Content-Disposition",   "attachment;filename=" + returnName);  
		response.setContentLength(byteArrayOutputStream.size());
		
		ServletOutputStream outputstream = response.getOutputStream();	//取得输出流
		byteArrayOutputStream.writeTo(outputstream);					//写到输出流
		byteArrayOutputStream.close();									//关闭
		outputstream.flush();											//刷数据
	}
}

【生成pdf报表的效果】
在这里插入图片描述

二、 报表管理(前端报表)

1. 前端报表生成技术 highcharts
前端报表技术,使用JavaScript 生成漂亮图表
百度echartshttp://echarts.baidu.com/examples.html
Funsioncharts Free(FCF): http://www.fusioncharts.com/goodies/fusioncharts-free/
Highchartshttp://www.highcharts.com/
折线图、 区域图、 柱状图、 饼状图 …

去掉highcharts.com的logo

在highcharts.js文件中找到credits,然后把enable的属性从!0改为0。
在这里插入图片描述

定制打印是否显示

在highcharts.html文件的js中设置以下代码:

exporting:{
enabled:true //用来设置是否显示‘打印’,'导出'等功能按钮,不设置时默认为显示,true表示显示打印,false表示不显示打印
},

在这里插入图片描述

< 如有问题,可联系(QQ : 1835134808),欢迎各位大佬提提不同见解>

猜你喜欢

转载自blog.csdn.net/weixin_42633131/article/details/83099388