利用Java Itext生成PDF文件并导出,实现效果如下:

PDFUtil.java

package com.jeeplus.modules.order.util;

import java.io.OutputStream;
import java.math.BigDecimal;
import java.net.URL;
import java.text.DecimalFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletResponse;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Chunk;
import com.itextpdf.text.Document;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfWriter;
import com.jeeplus.common.utils.Encodes;
import com.jeeplus.common.utils.StringUtils;
import com.jeeplus.modules.order.entity.OrderHeader;
import com.jeeplus.modules.order.entity.OrderLine;
import com.jeeplus.modules.order.service.PDFService;
import com.jeeplus.modules.sys.utils.UserUtils; public class PDFUtil { /**
*
* @param exhibitionName 展会名称
* @param orders 订单
* @param REMITTANCE_UNIT 收款单位
* @param REMITTANCE_BANK 收款银行
* @param REMITTANCE_ACCOUNT 收款账号
* @param SEAL_PICTURE_NAME 印章名称默认为深圳中智兴
* @param payUrl 系统网址
* @param response
* @throws Exception author:xiaofei.xian 日期:2018年5月30日 上午11:29:57
*/
public static void createPDF(String exhibitionName, List<OrderHeader> orders, String REMITTANCE_UNIT, String REMITTANCE_BANK,
String REMITTANCE_ACCOUNT, String SEAL_PICTURE_NAME, String payUrl, HttpServletResponse response) throws Exception {
// 生成PDF
Document document = new Document(PageSize.A4);
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font fontChinese = new Font(bfChinese, 12, Font.NORMAL);
Font fontMoney = new Font(bfChinese, 13, Font.BOLD, BaseColor.RED);
Font BlodFont = new Font(bfChinese, 12, Font.BOLD, BaseColor.BLACK); // 写入器
PdfWriter writer = PdfWriter.getInstance(document, response.getOutputStream());
// 只读
writer.setEncryption(null, null, PdfWriter.ALLOW_PRINTING, PdfWriter.STANDARD_ENCRYPTION_128);
// 通过PDF页面事件模式添加文字水印功能
writer.setPageEvent(new TextWaterMarkPdfPageEvent(REMITTANCE_UNIT)); // 添加页脚功能
document.open();
PdfPTable pdfPTable = new PdfPTable(1);
PdfFooterEvent footerTable = new PdfFooterEvent(pdfPTable, payUrl);
footerTable.setTableFooter(writer);
document.add(pdfPTable); // 添加PDF属性
document.open();
Paragraph pph1 = new Paragraph("预租确认回执", new Font(bfChinese, 20, Font.BOLD, BaseColor.BLACK));
pph1.setAlignment(Element.ALIGN_CENTER);
pph1.setSpacingAfter(10);
pph1.setSpacingBefore(5);
document.add(pph1);
// 6列的表.
PdfPTable table = new PdfPTable(6);
table.setTotalWidth(500);
table.setLockedWidth(true);
table.setHorizontalAlignment(Element.ALIGN_CENTER); // 第一行
PdfPCell cell1 = new PdfPCell(new Phrase("展会名称:" + exhibitionName, fontChinese));
cell1.setColspan(6);
table.addCell(cell1); StringBuffer boothNums = new StringBuffer();
for (OrderHeader orderHeader : orders) {
// 获取订单信息
boothNums.append(orderHeader.getExName() + ",");
} // 第二行
PdfPCell cell2 = new PdfPCell(new Phrase("展位编号:" + boothNums.toString().subSequence(0, boothNums.length() - 1), fontChinese));
cell2.setColspan(6);
table.addCell(cell2); // 第三行
PdfPCell cell3 = new PdfPCell(new Phrase("下单人:" + UserUtils.get(orders.get(0).getCreateBy()).getName(), fontChinese));
cell3.setColspan(6);
cell3.setHorizontalAlignment(Element.ALIGN_RIGHT);
table.addCell(cell3); // 第四行
PdfPCell cell4_1 = new PdfPCell(new Phrase("名称", fontChinese));
PdfPCell cell4_2 = new PdfPCell(new Phrase("规格", fontChinese));
PdfPCell cell4_3 = new PdfPCell(new Phrase("单价", fontChinese));
PdfPCell cell4_4 = new PdfPCell(new Phrase("押金", fontChinese));
PdfPCell cell4_5 = new PdfPCell(new Phrase("数量", fontChinese));
PdfPCell cell4_6 = new PdfPCell(new Phrase("小计", fontChinese));
table.addCell(cell4_1);
table.addCell(cell4_2);
table.addCell(cell4_3);
table.addCell(cell4_4);
table.addCell(cell4_5);
table.addCell(cell4_6); BigDecimal total = BigDecimal.ZERO; List<OrderLine> orderLines = new ArrayList<OrderLine>();
for (OrderHeader orderHeader : orders) {
orderLines = orderHeader.getOrderLines();
for (OrderLine orderLine : orderLines) {
cell4_1 = new PdfPCell(new Phrase(orderLine.getGoodsName(), fontChinese));
cell4_2 = new PdfPCell(new Phrase(orderLine.getSpecifications(), fontChinese));
cell4_3 = new PdfPCell(new Phrase(String.valueOf(orderLine.getUnitPrice()), fontChinese)); DecimalFormat df1 = new DecimalFormat("0.00");
String str = df1.format(orderLine.getForegift().multiply(orderLine.getBuyNum().subtract(orderLine.getEditForegiftPrice())));
cell4_4 = new PdfPCell(new Phrase(str, fontChinese));
cell4_5 = new PdfPCell(new Phrase(String.valueOf(orderLine.getBuyNum()), fontChinese));
cell4_6 =
new PdfPCell(new Phrase(String.valueOf((orderLine.getUnitPrice().add(orderLine.getForegift())).multiply(orderLine.getBuyNum())
.subtract(orderLine.getEditFeePrice().subtract(orderLine.getEditForegiftPrice()))), fontChinese));
total = total.add((orderLine.getUnitPrice().add(orderLine.getForegift())).multiply(orderLine.getBuyNum())
.subtract(orderLine.getEditFeePrice().subtract(orderLine.getEditForegiftPrice())));
table.addCell(cell4_1);
table.addCell(cell4_2);
table.addCell(cell4_3);
table.addCell(cell4_4);
table.addCell(cell4_5);
table.addCell(cell4_6);
}
} // 第六行
PdfPCell cell6 = new PdfPCell(new Phrase("总计:" + total, fontMoney));
cell6.setColspan(6);
table.addCell(cell6); // 第七行
PdfPCell cell7_1 = new PdfPCell(new Phrase("收款单位:", fontChinese));
PdfPCell cell7_2 = new PdfPCell(new Phrase(REMITTANCE_UNIT, fontChinese));
cell7_1.setHorizontalAlignment(Element.ALIGN_LEFT);
cell7_2.setHorizontalAlignment(Element.ALIGN_LEFT);
cell7_1.setColspan(2);
cell7_2.setColspan(4); table.addCell(cell7_1);
table.addCell(cell7_2); cell7_1 = new PdfPCell(new Phrase("开户行:", fontChinese));
cell7_2 = new PdfPCell(new Phrase(REMITTANCE_BANK, fontChinese));
cell7_1.setHorizontalAlignment(Element.ALIGN_LEFT);
cell7_2.setHorizontalAlignment(Element.ALIGN_LEFT);
cell7_1.setColspan(2);
cell7_2.setColspan(4); table.addCell(cell7_1);
table.addCell(cell7_2); cell7_1 = new PdfPCell(new Phrase("账号:", fontChinese));
cell7_2 = new PdfPCell(new Phrase(REMITTANCE_ACCOUNT, fontMoney));
cell7_1.setHorizontalAlignment(Element.ALIGN_LEFT);
cell7_2.setHorizontalAlignment(Element.ALIGN_LEFT);
cell7_1.setColspan(2);
cell7_2.setColspan(4); table.addCell(cell7_1);
table.addCell(cell7_2); // 第十行
PdfPCell cell10 = new PdfPCell(new Phrase(REMITTANCE_UNIT, fontChinese));
cell10.setHorizontalAlignment(Element.ALIGN_RIGHT);
cell10.setColspan(6);
table.addCell(cell10); document.add(table); // 默认为深圳中智兴
if (StringUtils.isEmpty(SEAL_PICTURE_NAME)) {
SEAL_PICTURE_NAME = "zzx_seal.png";
}
// 读入并设置印章图片
URL resource = PDFService.class.getResource("/sealimg/" + SEAL_PICTURE_NAME);
Image image = Image.getInstance(resource);
image.setScaleToFitLineWhenOverflow(true);
image.setAlignment(Element.ALIGN_RIGHT);
float x = table.getTotalWidth();
float y = 750 - table.getTotalHeight();
while (y < 0) {
y = 750 - (table.getTotalHeight() - 750);
}
image.setAbsolutePosition(x - 60, y);
image.scaleAbsolute(100, 100);
PdfContentByte pcb = writer.getDirectContentUnder();
pcb.addImage(image);
document.add(image);
document.add(Chunk.NEWLINE); // 特别提醒
Paragraph paragraphRemark = new Paragraph();
Font remarkFont = new Font(bfChinese, 10, Font.NORMAL);
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
paragraphRemark.add(new Chunk("特别提醒:", BlodFont));
paragraphRemark.add(Chunk.NEWLINE);
paragraphRemark.add(new Chunk("1.您的汇款识别码为", remarkFont));
paragraphRemark.add(new Chunk(orders.get(0).getRemitCode(), fontMoney));
paragraphRemark.add(new Chunk("。请将此识别码填写到汇款单【附言】栏内(仅填写此识别码),如未填写会影响订单确认时间。", remarkFont));
paragraphRemark.add(Chunk.NEWLINE);
paragraphRemark.add(Chunk.NEWLINE);
paragraphRemark.add(new Chunk("2.请将待支付款项在", remarkFont));
paragraphRemark.add(new Chunk(sdf.format(orders.get(0).getCancelDate()), fontMoney));
paragraphRemark.add(new Chunk("前通过银行汇到以上指定账号,请您尽快汇清款项,逾期订单将自动取消,汇款后请等待确认收款,到账周期一般为1-3个工作日。", remarkFont));
paragraphRemark.add(Chunk.NEWLINE);
paragraphRemark.add(Chunk.NEWLINE);
paragraphRemark.add(new Chunk("4.汇款金额请与应付金额保持一致,请勿多汇款或者少汇款。", remarkFont));
paragraphRemark.add(Chunk.NEWLINE);
document.add(paragraphRemark); sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");
pph1 = new Paragraph("打印日期:" + sdf.format(new Date()), fontChinese);
pph1.setAlignment(Element.ALIGN_RIGHT);
pph1.setSpacingBefore(20);
document.add(pph1);
response.setContentType("application/pdf; charset=utf-8");
response.setHeader("Content-Disposition", "attachment; filename=" + Encodes.urlEncode("预租确认回执") + ".pdf");
document.close();
writer.close();
OutputStream out = response.getOutputStream();
out.flush();
response.flushBuffer();
} }

水印事件TextWaterMarkPdfPageEvent.java

package com.jeeplus.modules.order.util;

import java.io.IOException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter; /**
* PDF 水印事件
*
* @author xiaofei.xian 日期:2018年5月30日 上午11:25:18
*/
public class TextWaterMarkPdfPageEvent extends PdfPageEventHelper { private String waterMarkText; public TextWaterMarkPdfPageEvent(String waterMarkText) {
this.waterMarkText = waterMarkText;
} @Override
public void onEndPage(PdfWriter writer, Document document) {
try {
float pageWidth = document.right() + document.left();// 获取pdf内容正文页面宽度
float pageHeight = document.top() + document.bottom();// 获取pdf内容正文页面高度
// 设置水印字体格式
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font waterMarkFont = new Font(base, 15, Font.BOLD, new BaseColor(230, 230, 230));
PdfContentByte waterMarkPdfContent = writer.getDirectContentUnder();
Phrase phrase = new Phrase(waterMarkText, waterMarkFont);
ColumnText.showTextAligned(waterMarkPdfContent, Element.ALIGN_CENTER, phrase, pageWidth * 0.25f, pageHeight * 0.2f, 45);
ColumnText.showTextAligned(waterMarkPdfContent, Element.ALIGN_CENTER, phrase, pageWidth * 0.25f, pageHeight * 0.5f, 45);
ColumnText.showTextAligned(waterMarkPdfContent, Element.ALIGN_CENTER, phrase, pageWidth * 0.25f, pageHeight * 0.8f, 45);
ColumnText.showTextAligned(waterMarkPdfContent, Element.ALIGN_CENTER, phrase, pageWidth * 0.65f, pageHeight * 0.2f, 45);
ColumnText.showTextAligned(waterMarkPdfContent, Element.ALIGN_CENTER, phrase, pageWidth * 0.65f, pageHeight * 0.5f, 45);
ColumnText.showTextAligned(waterMarkPdfContent, Element.ALIGN_CENTER, phrase, pageWidth * 0.65f, pageHeight * 0.8f, 45);
} catch (DocumentException de) {
de.printStackTrace();
} catch (IOException de) {
de.printStackTrace();
}
}
}

页脚事件PdfFooterEvent.java

package com.jeeplus.modules.order.util;

import java.io.IOException;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfPCell;
import com.itextpdf.text.pdf.PdfPTable;
import com.itextpdf.text.pdf.PdfPageEventHelper;
import com.itextpdf.text.pdf.PdfWriter; /**
* PDF 页眉事件
*
* @author xiaofei.xian 日期:2018年5月30日 上午11:25:00
*/
public class PdfFooterEvent extends PdfPageEventHelper { public static PdfPTable footer; public static String webUrl; public PdfFooterEvent(PdfPTable footer, String webUrl) {
PdfFooterEvent.footer = footer;
PdfFooterEvent.webUrl = webUrl;
} @Override
public void onEndPage(PdfWriter writer, Document document) {
// 把页脚表格定位
footer.writeSelectedRows(0, -1, 38, 30, writer.getDirectContent());
} /**
* 页脚是文字
*
* @param writer
* @param songti09
* @throws IOException
* @throws DocumentException
*/
public void setTableFooter(PdfWriter writer) throws DocumentException, IOException {
PdfPTable table = new PdfPTable(1);
table.setTotalWidth(520f);
PdfPCell cell = new PdfPCell();
cell.setBorder(1);
String string =
"本回执仅做财务付款申请凭证,它用无效 网址:" + webUrl;
BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font FontChinese = new Font(bfChinese, 10, Font.NORMAL);
FontChinese.setColor(new BaseColor(150, 150, 150));
Paragraph p = new Paragraph(string, FontChinese);
cell.setPaddingLeft(10f);
cell.setPaddingTop(-2f);
cell.addElement(p);
table.addCell(cell);
PdfFooterEvent event = new PdfFooterEvent(table, webUrl);
writer.setPageEvent(event);
}
}

Java Itext 生成PDF文件的更多相关文章

  1. Java 动态生成 PDF 文件

    每片文章前来首小诗:   今日夕阳伴薄雾,印着雪墙笑开颜.我心仿佛出窗前,浮在半腰望西天.  --泥沙砖瓦浆木匠 需求: 项目里面有需要java动态生成 PDF 文件,提供下载.今天我找了下有关了,系 ...

  2. Itext生成pdf文件

    来源:https://my.oschina.net/lujianing/blog/894365 1.背景 在某些业务场景中,需要提供相关的电子凭证,比如网银/支付宝中转账的电子回单,签约的电子合同等. ...

  3. 【Java】使用iText生成PDF文件

    iText介绍 iText是著名的开放源码的站点sourceforge一个项目,是用于生成PDF文档的一个java类库.通过iText不仅可以生成PDF或rtf的文档,而且可以将XML.Html文件转 ...

  4. 关于java poi itext生成pdf文件的例子以及方法

    最近正在做导出pdf文件的功能,所以查了了一些相关资料,发现不是很完善,这里做一些小小的感想,欢迎各位“猿”童鞋批评指正. poi+itext,所需要的jar包有itext-2.1.7.jar,poi ...

  5. itext 生成pdf文件添加页眉页脚

    原文来自:https://www.cnblogs.com/joann/p/5511905.html 我只是记录所有jar版本,由于版本冲突及不兼容很让人头疼的,一共需要5个jar, 其中itextpd ...

  6. 使用iText生成pdf文件

    前言 折腾了一早上的iText,下面主要介绍一下如何使用iText通过java代码生成pdf文档,以及如何输出包含中文的pdf文档. 首先,要说明的是,我用的是iText-7(java),下载链接是: ...

  7. [itext]Java生成PDF文件

    一.前言 最近在做也导出试卷的功能,刚开始是导出为doc,可是导出来格式都有变化,最后说直接将word转为pdf,可是各种不稳定,各种报错.最后想到直接将文件写入pdf(参考:http://www.c ...

  8. JAVA生成PDF文件

    生成PDF文件是主要应用的是ITEXT插件 import java.awt.Color; import java.io.File; import java.io.FileOutputStream; i ...

  9. java调用wkhtmltopdf生成pdf文件,美观,省事

    最近项目需要导出企业风险报告,文件格式为pdf,于是搜了一大批文章都是什么Jasper Report,iText ,flying sauser ,都尝试了一遍,感觉不是我想要的效果, 需要自己调整好多 ...

随机推荐

  1. 用Python实现阿里钉钉机器人读取数据库内容自动发群通知

    最近想把一些预警数据信息按照一定的要求自动发送到移动端APP,最终把目标放在了腾讯的微信和阿里的钉钉软件上,由于刚开始学习python,于是编程工具想用python来实现.微信使用群体最广,通过一天的 ...

  2. django中配置允许跨域请求

    对于django 安装django-cors-headers,详情请看官方文档 pip install django-cors-headers 配置settings.py文件 a.在INSTALLED ...

  3. 10 Python中的代码缓存机制

    目录: 1) 什么是代码块 2) 基本原理 3) 机制适用范围 4) 适用对象 5) 优势 更详细说明,参考太白老师博客 https://www.cnblogs.com/jin-xin/article ...

  4. Codeforces Round #395 C. Timofey and a tree

    package codeforces; import java.util.*; public class CodeForces_764C_Timofey_and_a_tree { static fin ...

  5. How to automate PowerPoint using VB

    Microsoft has an article that explains how to automate PowerPoint using VB For some odd reason they' ...

  6. POJ 1019 数学题

    #include <cstdio> #include <cstring> using namespace std; ]; //sum[i]表示尾数为i的组最大可达到的数字个数 ...

  7. hdu 1269 求连通图的模板题

    #include<stdio.h> #include<string.h> #include<iostream>//只存在一个连通分量 #include<str ...

  8. SGU -1500 - Pass Licenses

    先上题目: 1500. Pass Licenses Time limit: 2.5 secondMemory limit: 64 MB A New Russian Kolyan believes th ...

  9. JS中showModalDialog 详细使用方法

    基本介绍: showModalDialog() (IE 4+ 支持) showModelessDialog() (IE 5+ 支持) window.showModalDialog() 方法用来创建一个 ...

  10. Linux下汇编语言学习笔记77 ---

    这是17年暑假学习Linux汇编语言的笔记记录,参考书目为清华大学出版社 Jeff Duntemann著 梁晓辉译<汇编语言基于Linux环境>的书,喜欢看原版书的同学可以看<Ass ...