java生成pdf图表_Highcharts图表导出为pdf的JavaWeb实践

本文介绍了一个JavaWeb工具类`ComprehensivePdfUtil`,用于生成PDF并插入由Highcharts生成的SVG图表。该工具利用Apache Batik库将SVG转换为PNG,然后整合到iTextPDF生成的PDF中。方法`getPDFStream`接收请求,处理SVG图像,创建PDF页面,包括页头信息和水印,并添加图表到PDF文档中。
摘要由CSDN通过智能技术生成

packagecom.demo.utils;importjava.io.ByteArrayOutputStream;importjava.io.IOException;importjava.io.StringReader;importjava.io.UnsupportedEncodingException;importjava.net.MalformedURLException;importjava.net.URLDecoder;importjava.util.ArrayList;importjava.util.List;importjava.util.Map;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.apache.batik.transcoder.TranscoderException;importorg.apache.batik.transcoder.TranscoderInput;importorg.apache.batik.transcoder.TranscoderOutput;importorg.apache.batik.transcoder.image.PNGTranscoder;importcom.itextpdf.text.BadElementException;importcom.itextpdf.text.BaseColor;importcom.itextpdf.text.Document;importcom.itextpdf.text.DocumentException;importcom.itextpdf.text.Element;importcom.itextpdf.text.Font;importcom.itextpdf.text.Image;importcom.itextpdf.text.Paragraph;importcom.itextpdf.text.Phrase;importcom.itextpdf.text.Rectangle;importcom.itextpdf.text.pdf.BaseFont;importcom.itextpdf.text.pdf.PdfPCell;importcom.itextpdf.text.pdf.PdfPRow;importcom.itextpdf.text.pdf.PdfPTable;importcom.itextpdf.text.pdf.PdfWriter;/*** @Description XXX分析页面PDF导出工具方法*/

public classComprehensivePdfUtil {/*** 获得PDF字节输出流及pdf布局业务逻辑

*@paramrequest

*@paramresponse

*@paramresultMap 包含参数:svg(绘图svg参数及hicharts图布局参数) logoT(页面总标题)

*@paramlist 页面包含植入栏目排行表格图,该list存储绘制表格所用的数据

*@paramtableTh 页面包含植入栏目排行表格图,该字符串作为表格表头

*@paramtableTd 页面包含植入栏目排行表格图,该字符串作为表格内容填充时,实体类反射值所用的方法名(必须与实体方法严格一致)

*@return

*/

publicByteArrayOutputStream getPDFStream(HttpServletRequest request,

HttpServletResponse response,

MapresultMap){try{//图片变量定义

String noData = "/style/images/noData.png";//无数据左右图

String noDataCenter = "/style/images/noDataCenter.png";//无数据中间图

String waterMark = "/style/images/PDFSHUIYIN.png";//PDF导出文件水印图片

String [] svgName = (String[]) resultMap.get("svg");//导出PDF页面所有svg图像

Document document = newDocument();

ByteArrayOutputStream buffer= newByteArrayOutputStream();

PdfWriter pdfWriter=PdfWriter.getInstance(document, buffer);//设置页面大小

int pageHeight = 2000;

Rectangle rect= new Rectangle(0,0,1200,pageHeight);

rect.setBackgroundColor(new BaseColor(248,248,248));//页面背景色

document.setPageSize(rect);//页面参数//页边空白

document.setMargins(20, 20, 30, 20);

document.open();//设置页头信息

if(null!=resultMap.get("logoT")){

BaseFont bfChinese= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

Font FontChinese= new Font(bfChinese,20, Font.BOLD);

Paragraph paragraph= new Paragraph((String)resultMap.get("logoT"),FontChinese);

paragraph.setAlignment(Element.ALIGN_CENTER);

document.add(paragraph);

}

PdfPTable table= null;

String path=request.getContextPath();

String basePath= request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";//开始循环写入svg图像到pdf文档对象

for(String str:svgName){//

//positionAndSvg数组中元素说明://positionAndSvg[0]表示svg图像所在页面的div的id//positionAndSvg[1]表示svg图像在水平方向的相对位置://1.left(水平方向两张图,居左且占比50%)//2.right(水平方向两张图,居右且占比50%)//3.center(水平方向一张图,居中且占比100%)//positionAndSvg[2]表示svg图像模块的标题如:xxx走势图//positionAndSvg[3]表示soft/hard即软广图或者硬广图,当无数据时为无数据提示效果图提供判断依据//positionAndSvg[4]表示svg图像元素,形如

// String[] positionAndSvg = str.split("___");

Image image1= null;boolean havaData = true;if("noData".equals(positionAndSvg[4])){//无数据时

image1 = Image.getInstance(basePath+noData);

havaData= false;

}else{//有数据

image1 = Image.getInstance(highcharts(request,response,positionAndSvg[4]).toByteArray());

havaData= true;

}if("left".equals(positionAndSvg[1])){

String title1= URLDecoder.decode(positionAndSvg[2],"utf-8");

setTitleByCharts(document,30,title1,"",0,87,55,Element.ALIGN_LEFT,headfont);if(!"cooperateProporOne".equals(positionAndSvg[0])){

setTitleByCharts(document,0,"左图","右图",248,248,248,Element.ALIGN_CENTER,blackTextFont);

}else{

setTitleByCharts(document,0,"","",248,248,248,Element.ALIGN_CENTER,blackTextFont);

}

table= new PdfPTable(2);float[] wid ={0.50f,0.50f}; //列宽度的比例

table.setWidths(wid);

table=PdfPTableImage(table,image1,80f);

}else if("right".equals(positionAndSvg[1])){

table=PdfPTableImage(table,image1,80f);

table.setSpacingBefore(10);

table=setTableHeightWeight(table,360f,1000);

document.add(table);

table= null;

}else if("center".equals(positionAndSvg[1])){//总览全局

String title1 = URLDecoder.decode(positionAndSvg[2],"utf-8");

setTitleByCharts(document,30,title1,"",0,87,55,Element.ALIGN_LEFT,headfont);

setTitleByCharts(document,0,"","",248,248,248,Element.ALIGN_CENTER,blackTextFont);

table= new PdfPTable(1);float[] wid ={1.00f}; //列宽度的比例

table.setWidths(wid);if(havaData){

table=PdfPTableImageTable(table,image1,1000f,600f);

}else{

table= PdfPTableImageTable(table,Image.getInstance(basePath+noDataCenter),1000f,600f);

}

table=setTableHeightWeight(table,400f,1000);

document.add(table);

table=null;

}

}//添加水印Start---------------------------------------------------------------------------------------------

PdfFileExportUtil pdfFileExportUtil = newPdfFileExportUtil();

pdfWriter.setPageEvent(pdfFileExportUtil.new PictureWaterMarkPdfPageEvent(basePath+waterMark));//pdfWriter.setPageEvent(pdfFileExportUtil.new TextWaterMarkPdfPageEvent("xxx科技"));//添加水印End-----------------------------------------------------------------------------------------------

document.close();returnbuffer;

}catch(BadElementException e) {

e.printStackTrace();return null;

}catch(MalformedURLException e) {

e.printStackTrace();return null;

}catch(DocumentException e) {

e.printStackTrace();return null;

}catch(IOException e) {

e.printStackTrace();return null;

}catch(Exception e) {

e.printStackTrace();return null;

}

}/*** 设置图片类型Cell属性

*@paramtable

*@paramimage1

*@paramimgPercent

*@return*@throwsException*/

private PdfPTable PdfPTableImage(PdfPTable table,Image image1,floatimgPercent){

table=useTable(table,Element.ALIGN_CENTER);

PdfPCell cellzr=createCellImage(image1,imgPercent);

cellzr.setBorder(0);

cellzr.setBackgroundColor(new BaseColor(248,248,248));

table.addCell(cellzr);returntable;

}/*** 设置图片类型Table的Cell属性

*@paramtable

*@paramimage1

*@paramimgPercentWidth

*@paramimgPercentHeight

*@return*@throwsException*/

private PdfPTable PdfPTableImageTable(PdfPTable table,Image image1,float imgPercentWidth,floatimgPercentHeight){

table=useTable(table,Element.ALIGN_CENTER);

PdfPCell cellzr=createCellImageTable(image1,imgPercentWidth,imgPercentHeight);

cellzr.setBorder(0);

cellzr.setBackgroundColor(new BaseColor(248,248,248));

table.addCell(cellzr);returntable;

}/*** 设置表头

*@paramdocument

*@paramSpacingBefore

*@paramtitle1

*@paramtitle2

*@paramr1

*@paramr2

*@paramr3

*@paramele

*@paramfont

*@throwsException*/

private void setTitleByCharts(Document document,int SpacingBefore,String title1,String title2,int r1,int r2,int r3,intele,Font font){try{float[] titlewidthsLeft = {0.50f,0.50f};

PdfPTable zrfbtitleTable=createTable(titlewidthsLeft);

PdfPCell cellzr=createCellLeft(title1,font,ele);

cellzr.setBorder(0);

cellzr.setBackgroundColor(newBaseColor(r1,r2,r3));

zrfbtitleTable.addCell(cellzr);

PdfPCell cellzr1=createCellLeft(title2,font,ele);

cellzr1.setBorder(0);

cellzr1.setBackgroundColor(newBaseColor(r1,r2,r3));

zrfbtitleTable.addCell(cellzr1);

zrfbtitleTable.setSpacingBefore(SpacingBefore);

zrfbtitleTable=setTableHeightWeight(zrfbtitleTable,30f,1000);

document.add(zrfbtitleTable);

}catch(DocumentException e) {

e.printStackTrace();

}

}/*** 导出Pdf所用字体静态变量*/

private static Font headfont ;//title字体

private static Font blackTextFont ;//黑色字体

private staticFont colorfont;int maxWidth = 500;static{

BaseFont bfChinese;try{

bfChinese= BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);

headfont= new Font(bfChinese, 15, Font.BOLD);//设置字体大小

headfont.setColor(BaseColor.WHITE);

blackTextFont= new Font(bfChinese, 11, Font.BOLD);//设置字体大小

blackTextFont.setColor(BaseColor.BLACK);

colorfont= new Font(bfChinese, 11, Font.NORMAL);//设置字体大小

colorfont.setColor(BaseColor.RED);

}catch(Exception e) {

e.printStackTrace();

}

}/*** 创建指定内容背景色的Table元素Cell

*@paramvalue

*@paramfont

*@paramc1

*@paramc2

*@paramc3

*@return

*/

public PdfPCell createCell(String value,Font font,int c1,int c2, intc3){

PdfPCell cell= newPdfPCell();

cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

cell.setHorizontalAlignment(Element.ALIGN_CENTER);

cell.setPhrase(newPhrase(value,font));

cell.setBackgroundColor(newBaseColor(c1,c2,c3));

cell.setFixedHeight(33.33f);

cell.setBorder(0);returncell;

}/*** 创建指定位置的Table元素Cell

*@paramvalue

*@paramfont

*@paramele

*@return

*/

public PdfPCell createCellLeft(String value,Font font,intele){

PdfPCell cell= newPdfPCell();

cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

cell.setHorizontalAlignment(ele);

cell.setPaddingLeft(10);

cell.setPhrase(newPhrase(value,font));returncell;

}/*** 创建内容为Image的Table元素Cell

*@paramimage

*@paramimgPercent

*@return

*/

public PdfPCell createCellImage(Image image,floatimgPercent){

image.scalePercent(imgPercent);

PdfPCell cell= new PdfPCell(image,false);

cell.setUseAscender(true);

cell.setUseDescender(true);

cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

cell.setHorizontalAlignment(Element.ALIGN_CENTER);

cell.setPaddingLeft(10);returncell;

}/*** 创建table元素cell

*@paramimage

*@paramimgPercentWidth

*@paramimgPercentHeight

*@return

*/

public PdfPCell createCellImageTable(Image image,float imgPercentWidth,floatimgPercentHeight){

image.scaleAbsoluteWidth(imgPercentWidth);if(imgPercentHeight==410f){

image.scaleAbsoluteHeight(imgPercentHeight);

}

PdfPCell cell= new PdfPCell(image,false);

cell.setVerticalAlignment(Element.ALIGN_MIDDLE);

cell.setHorizontalAlignment(Element.ALIGN_CENTER);returncell;

}/*** 创建Table

*@paramwidths 列宽比例

*@return

*/

public PdfPTable createTable(float[] widths){for(int i=0;i

widths[i]= widths[i]*maxWidth;

}

PdfPTable table= newPdfPTable(widths);try{

table.setTotalWidth(maxWidth);

table.setLockedWidth(true);

table.setHorizontalAlignment(Element.ALIGN_CENTER);

table.getDefaultCell().setBorder(1);

}catch(Exception e){

e.printStackTrace();

}returntable;

}/*** 设置table参数

*@paramtable

*@paramposition

*@return

*/

public PdfPTable useTable(PdfPTable table,intposition){try{

table.setTotalWidth(maxWidth);

table.setLockedWidth(true);

table.setHorizontalAlignment(position);

table.getDefaultCell().setBorder(0);

}catch(Exception e){

e.printStackTrace();

}returntable;

}/*** 设置PdfTable行高

*@paramtable

*@parammaxHeight

*@parammaxWidth

*@return

*/

public PdfPTable setTableHeightWeight(PdfPTable table,float maxHeight,floatmaxWidth){

table.setTotalWidth(maxWidth);

List list=new ArrayList();

list=table.getRows();for(PdfPRow pr:list){

pr.setMaxHeights(maxHeight);

}returntable;

}/*** 根据SVG字符串得到一个输出流

*@paramrequest

*@paramresponse

*@paramsvg

*@return*@throwsException*/

publicByteArrayOutputStream highcharts(HttpServletRequest request,HttpServletResponse response,String svg){try{

request.setCharacterEncoding("utf-8");//注意编码//转码防止乱码

byte[] arrayStr = svg.getBytes("utf-8");

svg= new String(arrayStr, "UTF-8");

ByteArrayOutputStream stream= newByteArrayOutputStream();try{

stream=this.transcode(stream, svg);

}catch(Exception e) {

e.printStackTrace();

}returnstream;

}catch(UnsupportedEncodingException e) {

e.printStackTrace();return null;

}

}/*** 对svg进行转码

*@paramstream

*@paramsvg

*@return*@throwsException*/

public synchronizedByteArrayOutputStream transcode(ByteArrayOutputStream stream, String svg){try{

TranscoderInput input= new TranscoderInput(newStringReader(svg));

TranscoderOutput transOutput= newTranscoderOutput(stream);

PNGTranscoder transcoder= newPNGTranscoder();

transcoder.transcode(input, transOutput);returnstream;

}catch(TranscoderException e) {

e.printStackTrace();return null;

}

}

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值