java使用IText下载PDF
1.引入IText有关的Maven依赖项如下:
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.11</version>
</dependency>
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itext-asian</artifactId>
<version>5.2.0</version>
</dependency>
<dependency>
<groupId>com.itextpdf.tool</groupId>
<artifactId>xmlworker</artifactId>
<version>5.5.11</version>
</dependency>
2. 利用IText创建PDF的五个基础步骤:
(1) 设置浏览器兼容模式
String userAgent = request.getHeader("User-Agent");
if (userAgent.contains("MSIE") || userAgent.contains("Trident")) {
filename = java.net.URLEncoder.encode(filename, "UTF-8");
} else {
// 非IE浏览器的处理:
filename = new String(filename.getBytes("UTF-8"), "ISO-8859-1");
}
response.reset();
response.setHeader("Content-Disposition", "attachment; filename=\"" + filename + "\"");
response.setContentType("application/octet-stream;charset=UTF-8");
(2) 创建com.itextpdf.text.Document对象:
//创建文件(A4纸大小)
Document document = new Document(PageSize.A4);
Rectangle one = new Rectangle(730,820);
document.setPageSize(one);
该类是IText中用于定义PDF文档的类,其有三个构造函数:
1)第一构造函数默认以A4页面作为参数;
public Document() {
this(PageSize.A4);
}
2)第二个构造函数用户可自定义页面大小,且默认情况下以每边36磅页边距为参数调用3)个构造函数;
public Document(Rectangle pageSize) {
this(pageSize, 36.0F, 36.0F, 36.0F, 36.0F);
}
3)第三个构造函数用户可自定义页面大小以及页面边距,并设置了其他相关默认值
public Document(Rectangle pageSize, float marginLeft, float marginRight, float marginTop, float marginBottom) {
this.listeners = new ArrayList();
this.marginLeft = 0.0F;
this.marginRight = 0.0F;
this.marginTop = 0.0F;
this.marginBottom = 0.0F;
this.marginMirroring = false;
this.marginMirroringTopBottom = false;
this.javaScript_onLoad = null;
this.javaScript_onUnLoad = null;
this.htmlStyleClass = null;
this.pageN = 0;
this.chapternumber = 0;
this.role = PdfName.DOCUMENT;
this.accessibleAttributes = null;
this.id = new AccessibleElementId();
this.pageSize = pageSize;
this.marginLeft = marginLeft;
this.marginRight = marginRight;
this.marginTop = marginTop;
this.marginBottom = marginBottom;
}
(3) 设置Document对象的属性:
BufferedOutputStream outputStream = new BufferedOutputStream(response.getOutputStream());
//创建文件(默认A4纸大小)
Document document = new Document(PageSize.A4);
//设置页面大小
Rectangle one = new Rectangle(730,820);
//页面背景色
one.setBackgroundColor(BaseColor.ORANGE);
document.setPageSize(one);
//建立一个书写器(Writer)与document对象关联,通过书写器(Writer)可以将文档写入到磁盘中。
//创建 PdfWriter 对象 第一个参数是对文档对象的引用,第二个参数是文件的实际名称,在该名称中还会给出其输出路径。
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
//PDF版本(默认1.4)
writer.setPdfVersion(PdfWriter.PDF_VERSION_1_2);
//打开文件
document.open();
//添加Page,把这个方法放到for循环中可以生成多个pdf页。
document.newPage();
//中文字体,解决中文不能显示问题
//pdf输出中文的三种字体选择方式,请参考:https://blog.csdn.net/muriyue6/article/details/97747725
BaseFont bfChinese = BaseFont.createFont("STSong-Light","UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);
//设置空行
Font FontChinese18 = new Font(bfChinese, 18, Font.BOLD);
Paragraph blankRow1 = new Paragraph(18f, " ", FontChinese18);
//添加空行
document.add(blankRow1);
//创建一条直线(直线)
LineSeparator lineSeparator = new LineSeparator();
lineSeparator.setLineColor(BaseColor.GRAY);
//添加一条直线
document.add(new Chunk(lineSeparator));
//标题字体样式设置,Font第一个参数是设置字体的编码格式,第二个参数是设置字体的大小,第三个参数是设置字体的边框样式
//中文标题字体样式设置
Font blackFont = new Font(bfChinese,15,Font.BOLD);
blackFont.setColor(BaseColor.BLACK);
//英文标题字体样式设置
Font blackFont = new Font(BaseFont.createFont(),15,Font.BOLD);
blackFont.setColor(BaseColor.BLACK);
//添加标题名称
Paragraph titleOne= new Paragraph("ITINERARY", blackFont);
titleOne.setAlignment(Element.ALIGN_CENTER);
document.add(titleOne);
//创建表格对象,且设置表格列数(如下是创建了一个9列的表格对象)
PdfPTable tableTop = new PdfPTable(9);
// 宽度100%填充
tableTop.setWidthPercentage(100);
//获取表格行数
List<PdfPRow> listRowTop = tableTop.getRows();
//创建一个单元格数组,注意单元格数组的长度和表格的列数保持一致。
PdfPCell cellsTop[]= new PdfPCell[9];
//创建表格的一个空行
PdfPRow rowTop = new PdfPRow(cellsTop);
//添加单元格内容,第一个参数是填充的单元格内容,第二个参数是字体样式的设置
cellsTop[0] = new PdfPCell(new Paragraph("AIRLINE PNR: ",tableFont));
//设置字体在单元格中的位置,此处是水平居右
cellsTop[0].setHorizontalAlignment(Element.ALIGN_LEFT);
//横向合并单元格,此处是把第一个单元格和第二个单元格横向合并
cellsTop[0].setColspan(2);
//不设置边框
cellsTop[0].setBorder(0);
//数据
cellsTop[2] = new PdfPCell(new Paragraph(model.get("xxx") != " " ? model.get("xxx").toString() : " ",tableFont));//单元格内容
cellsTop[2].setHorizontalAlignment(Element.ALIGN_LEFT);//水平居左
cellsTop[2].setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
cellsTop[2].setColspan(3);
cellsTop[2].setBorder(0);
cellsTop[5] = new PdfPCell(new Paragraph("1E PNR: ",tableFont));//单元格内容
cellsTop[5].setHorizontalAlignment(Element.ALIGN_LEFT);//水平居右
cellsTop[5].setColspan(2);
cellsTop[5].setBorder(0); //不设置边框
cellsTop[7] = new PdfPCell(new Paragraph(model.get("xxx") != " " ? model.get("xxx").toString() : " ",tableFont));//单元格内容
cellsTop[7].setHorizontalAlignment(Element.ALIGN_LEFT);//水平居左
cellsTop[7].setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
cellsTop[7].setColspan(2);
cellsTop[7].setBorder(0);
//把创建的单元格空数据添加到表格的行中
listRowTop.add(rowTop);
//添加表格到PDF文档中
document.add(tableTop);
//创建第二个表格对象
PdfPTable table = new PdfPTable(11);
//宽度100%填充
table.setWidthPercentage(100);
//添加表格对象的列名内容
List<PdfPRow> listRow = table.getRows();
//列名
String columnNames[] = {"ORIGIN/\nDES",
"FLIGHT",
"CLASS",
"DATE",
"TIME",
"ARRTIME",
"PERIOD",
"STATUS",
"ALLOW",
"TERMINAL\n\n" + "Takeoff Arriva\n"};
PdfPCell cells[]= new PdfPCell[11];
//行
PdfPRow row = new PdfPRow(cells);
//设置列名
for(int j = 0; j < columnNames.length; j++ ) {
cells[j] = new PdfPCell(new Paragraph(columnNames[j],textFont));//单元格内容
cells[j].setHorizontalAlignment(Element.ALIGN_CENTER);//水平居中
cells[j].setVerticalAlignment(Element.ALIGN_MIDDLE);//垂直居中
cells[j].disableBorderSide(12); //隐藏左、右边框
//cells[i].setBorder(PdfPCell.BOX);
if (j == (columnNames.length - 1)){
cells[j].setColspan(2);
}
}
//把第一行添加到集合(添加第二个表格的第一行数据)
listRow.add(row);
//通过遍历对象数组动态添加表格数据
List<IntlOrderSegment> intlOrderSegmentList = (List<IntlOrderSegment>)model.get("intlOrderSegmentList");
if (intlOrderSegmentList != null && !intlOrderSegmentList.isEmpty()){
for (int j = 0; j < intlOrderSegmentList.size(); j++) {
IntlOrderSegment intlOrderSegment = intlOrderSegmentList.get(j);
PdfPCell cells1[]= new PdfPCell[11];
PdfPRow row1 = new PdfPRow(cells1);
//始发地/目的地
String arrCode = intlOrderSegment.getDepCode();
//单元格内容
cells1[0] = new PdfPCell(new Paragraph(arrCode,textFont));
//水平居中
cells1[0].setHorizontalAlignment(Element.ALIGN_CENTER);
//垂直居中
cells1[0].setVerticalAlignment(Element.ALIGN_MIDDLE);
cells1[0].setBorder(0);
//航班
//单元格内容
cells1[1] = new PdfPCell(new Paragraph(intlOrderSegment.getFlightNo(),textFont));
//水平居中
cells1[1].setHorizontalAlignment(Element.ALIGN_CENTER);
//垂直居中
cells1[1].setVerticalAlignment(Element.ALIGN_MIDDLE);
cells1[1].setBorder(0);
//座位等级
String cabinClass = intlOrderSegment.getCabinClass();
//单元格内容
cells1[2] = new PdfPCell(new Paragraph(cabinClass,textFont));
//水平居中
cells1[2].setHorizontalAlignment(Element.ALIGN_CENTER);
//垂直居中
cells1[2].setVerticalAlignment(Element.ALIGN_MIDDLE);
cells1[2].setBorder(0);
//日期
Date depDate = intlOrderSegment.getDepDate();
String depDateFormat = "";
if (depDate != null){
SimpleDateFormat sdf = new SimpleDateFormat("MM-dd");
depDateFormat = sdf.format(depDate);
}
//单元格内容
cells1[3] = new PdfPCell(new Paragraph(depDateFormat,textFont));
//水平居中
cells1[3].setHorizontalAlignment(Element.ALIGN_CENTER);
//垂直居中
cells1[3].setVerticalAlignment(Element.ALIGN_MIDDLE);
cells1[3].setBorder(0);
//起飞时间
//单元格内容
cells1[4] = new PdfPCell(new Paragraph(intlOrderSegment.getDepTime(),textFont));
//水平居中
cells1[4].setHorizontalAlignment(Element.ALIGN_CENTER);
//垂直居中
cells1[4].setVerticalAlignment(Element.ALIGN_MIDDLE);
cells1[4].setBorder(0);
//到达时间
//单元格内容
cells1[5] = new PdfPCell(new Paragraph(intlOrderSegment.getArrTime(),textFont));
//水平居中
cells1[5].setHorizontalAlignment(Element.ALIGN_CENTER);
//垂直居中
cells1[5].setVerticalAlignment(Element.ALIGN_MIDDLE);
cells1[5].setBorder(0);
//有效期
Date effectiveDate = intlOrderSegment.getDepDate();
String effectiveDateFormat = "";
if (effectiveDate != null){
Calendar cal = Calendar.getInstance();
cal.setTime(effectiveDate);
cal.add(Calendar.YEAR, 1);//增加一年
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
effectiveDateFormat = sdf.format(cal.getTime());
}
//单元格内容
cells1[6] = new PdfPCell(new Paragraph(effectiveDateFormat,textFont));
//水平居中
cells1[6].setHorizontalAlignment(Element.ALIGN_CENTER);
//垂直居中
cells1[6].setVerticalAlignment(Element.ALIGN_MIDDLE);
cells1[6].setBorder(0);
//客票状态
//单元格内容
cells1[7] = new PdfPCell(new Paragraph(StringUtils.isNotBlank(intlOrderSegment.getSeatClass()) ? "OK" : "",textFont));
//水平居中
cells1[7].setHorizontalAlignment(Element.ALIGN_CENTER);
//垂直居中
cells1[7].setVerticalAlignment(Element.ALIGN_MIDDLE);
cells1[7].setBorder(0);
//行李
String freeBaggageAllowance = intlOrderSegment.getFreeBaggageAllowance();
if (StringUtils.isNotBlank(freeBaggageAllowance)){
if (freeBaggageAllowance.contains("件")){
freeBaggageAllowance = freeBaggageAllowance.replace("件","PC");
}else if (freeBaggageAllowance.contains("公斤")){
freeBaggageAllowance = freeBaggageAllowance.replace("公斤","KG");
}
}
//单元格内容
cells1[8] = new PdfPCell(new Paragraph(freeBaggageAllowance,textFont));
//水平居中
cells1[8].setHorizontalAlignment(Element.ALIGN_CENTER);
//垂直居中
cells1[8].setVerticalAlignment(Element.ALIGN_MIDDLE);
cells1[8].setBorder(0);
//航站楼
String depTerm = intlOrderSegment.getDepTerm();
String term = = " " + depTerm + intlOrderSegment.getArrTerm();
//单元格内容
cells1[9] = new PdfPCell(new Paragraph(term,textFont));
//水平居中
cells1[9].setHorizontalAlignment(Element.ALIGN_CENTER);
//垂直居中
cells1[9].setVerticalAlignment(Element.ALIGN_MIDDLE);
cells1[9].setColspan(2);
cells1[9].setBorder(0);
//遍历添加每一行的数据
listRow.add(row1);
}
}
//把表格添加到PDF文件中
document.add(table);
//添加段落信息
document.add(new Paragraph("IF YOU NEED ANY ASSISTANCE, PLEASE CALL ME.",textFont));
//关闭文档
document.close();