在Java代码中使用iTextPDF生成PDF
1. 生成PDF
载入字体
static {
FontFactory.register("/fonts/msyh.ttf");
FontFactory.register("/fonts/msyhbd.ttf");
FontFactory.register("/fonts/simsun.ttc");
FontFactory.register("/fonts/simhei.ttf");
}
生成PDF
Rectangle rectPageSize = new Rectangle(PageSize.A4);// A4纸张
Document document = new Document(rectPageSize, 40, 40, 40, 40);// 上、下、左、右间距
try {
String filePath = StaticConfig.getConfig("file_path") + invest.getContractPath();
String folderPath = filePath.substring(0, filePath.lastIndexOf("/") + 1);
File folder = new File(folderPath);
if (!folder.exists()) {
folder.mkdirs();
} PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(filePath));
writer.setPdfVersion(PdfWriter.PDF_VERSION_1_7);
document.addCreationDate();
document.addCreator("rockbb");
document.addTitle("rockbbPDF");
document.addKeywords("export");
document.addSubject("rockbb业务文件");
document.open();
Font yahei9px = FontFactory.getFont("微软雅黑", BaseFont.IDENTITY_H, 9);
Font yahei10px = FontFactory.getFont("微软雅黑", BaseFont.IDENTITY_H, 10);
Font yahei11px = FontFactory.getFont("微软雅黑", BaseFont.IDENTITY_H, 11);
Font yahei12px = FontFactory.getFont("微软雅黑", BaseFont.IDENTITY_H, 12); document.add(paragraph("编号:[" + invest.getContractSn() + "]", yahei9px, Paragraph.ALIGN_RIGHT)); //表格
PdfPTable table = new PdfPTable(3);
table.setSpacingBefore(10.0f);
table.setWidthPercentage(100);
table.setWidths(new float[]{0.25f, 0.25f, 0.5f}); PdfPCell cell = cell("当事方", yahei11px, Element.ALIGN_CENTER, Element.ALIGN_MIDDLE);
cell.setColspan(3);
table.addCell(cell); cell = cell("甲方(投资者)", yahei10px);
cell.setRowspan(3);
table.addCell(cell);
table.addCell(cell("姓名", yahei10px));
table.addCell(cell(user.getRealName(), yahei10px));
table.addCell(cell("用户ID", yahei10px));
table.addCell(cell(user.getTel(), yahei10px));
table.addCell(cell("身份证", yahei10px));
table.addCell(cell(user.getIdNumber(), yahei10px)); cell = cell("乙方", yahei10px);
cell.setRowspan(3);
table.addCell(cell);
table.addCell(cell("名称", yahei10px));
table.addCell(cell("公司", yahei10px));
table.addCell(cell("住所", yahei10px));
table.addCell(cell("北京市朝阳区", yahei10px));
table.addCell(cell("注册证", yahei10px));
table.addCell(cell("", yahei10px));
document.add(table); document.add(paragraph("* 凡本协议未列示的产品信息以平台产品说明书页面显示的产品具体信息为准。", yahei9px)); document.add(paragraph("第二部分 协议条款", yahei12px, Paragraph.ALIGN_LEFT, 10.0f)); document.add(paragraph(agreement, yahei10px, Paragraph.ALIGN_LEFT, 5.0f)); document.close();
writer.close(); } catch (FileNotFoundException e) {
logger.error("FileNotFoundException");
logger.debug(e.getMessage(), e);
} catch (IOException e) {
logger.error("IOException");
logger.debug(e.getMessage(), e);
} catch (DocumentException e) {
logger.error("DocumentException");
logger.debug(e.getMessage(), e);
}
工具方法
private static PdfPCell cell(String content, Font font) {
PdfPCell cell = new PdfPCell(new Phrase(content, font));
cell.setBorderColor(new BaseColor(196, 196, 196));
cell.setPadding(5.0f);
cell.setPaddingTop(1.0f);
return cell;
}
private static PdfPCell cell(String content, Font font, int hAlign, int vAlign) {
PdfPCell cell = new PdfPCell(new Phrase(content, font));
cell.setBorderColor(new BaseColor(196, 196, 196));
cell.setVerticalAlignment(vAlign);
cell.setHorizontalAlignment(hAlign);
cell.setPadding(5.0f);
cell.setPaddingTop(1.0f);
return cell;
}
private static Paragraph paragraph(String content, Font font) {
return new Paragraph(content, font);
}
private static Paragraph paragraph(String content, Font font, int hAlign) {
Paragraph paragraph = new Paragraph(content, font);
paragraph.setAlignment(hAlign);
return paragraph;
}
private static Paragraph paragraph(String content, Font font, int hAlign, float spacingBefore) {
Paragraph paragraph = new Paragraph(content, font);
paragraph.setAlignment(hAlign);
paragraph.setSpacingBefore(spacingBefore);
return paragraph;
}
在生成过程中加盖图片, 注意, 因为无法指定页码, 所以这段代码要放到你需要加盖图片的那页对应的代码上
byte[] bytes = FileUtil.readResourceImage("/text/stamp.png");
if (bytes != null) {
Image image = Image.getInstance(bytes);
PdfContentByte canvas = writer.getDirectContent();
writer.getPageNumber();
// float width = image.getScaledWidth();
// float height = image.getScaledHeight();
canvas.addImage(image, 150, 0, 0, 150, rectPageSize.getWidth() - 300, rectPageSize.getHeight() - 300);
} else {
logger.error("Failed to read /text/stamp.png");
}
读取项目资源文件的工具方法
/**
* 读取项目图片资源文件
*
* @param filePath 以'/'开头的项目资源文件路径
* @return
*/
public static byte[] readResourceImage(String filePath) {
try {
InputStream is = FileUtil.class.getResourceAsStream(filePath);
BufferedImage image = ImageIO.read(is);
is.close();
ByteArrayOutputStream os = new ByteArrayOutputStream();
ImageIO.write(image, "png", os);
return os.toByteArray();
} catch (FileNotFoundException e) {
logger.error("FileNotFoundException: " + filePath);
} catch (IOException e) {
logger.error("IOException");
}
return null;
} /**
* 读取项目资源文件内容
*
* @param filePath 以'/'开头的项目资源文件路径
* @return 文件内容
*/
public static String readResourceContent(String filePath) {
StringBuilder sb = new StringBuilder();
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(FileUtil.class.getResourceAsStream(filePath)));
String line;
while ((line = reader.readLine()) != null) {
sb.append(line);
sb.append("\n");
}
reader.close();
} catch (FileNotFoundException e) {
logger.error("FileNotFoundException: " + filePath);
} catch (IOException e) {
logger.error("IOException");
}
return sb.toString();
}
在Java代码中使用iTextPDF生成PDF的更多相关文章
- 在Java代码中使用pdfBox将PDF转换为图片
生成图片 // 生成图片 PDDocument pd = PDDocument.load(new File(filePath)); PDFRenderer pdfRenderer = new PDFR ...
- java代码中fastjson生成字符串和解析字符串的方法和javascript文件中字符串和json数组之间的转换方法
1.java代码中fastjson生成字符串和解析字符串的方法 List<TemplateFull> templateFulls = new ArrayList<TemplateFu ...
- wsdl自动生成Java代码,根据wsdl生成Java代码
wsdl自动生成Java代码,根据wsdl生成Java代码 >>>>>>>>>>>>>>>>>&g ...
- 【转】使用JavaParser获得Java代码中的类名、方法形参列表中的参数名以及统计总的文件个数与不能解析的文件个数
遍历目录查找Java文件: public static void ergodicDir(File dir, HashSet<String> argNameSet, HashSet<S ...
- IDEA插件:快速删除Java代码中的注释
背景 有时,我们需要删除Java源代码中的注释.目前有不少方法,比如: 实现状态机.该方式较为通用,适用于多种语言(取决于状态机支持的注释符号). 正则匹配.该方式容易误判,尤其是容易误删字符串. ...
- Spring MVC框架下在java代码中访问applicationContext.xml文件中配置的文件(可以用于读取配置文件内容)
<bean id="propertyConfigurer" class="com.****.framework.core.SpringPropertiesUtil& ...
- 使用mongo-java-driver3.0.2.jar和mongodb3.0在java代码中的用户验证4
以下是使用mongo-java-driver3.0.2.jar和mongodb3.0.4在java代码中的用户验证: ServerAddress sa = new ServerAddress(host ...
- Android color(颜色) 在XML文件和java代码中
Android color(颜色) 在XML文件和java代码中,有需要的朋友可以参考下. 1.使用Color类的常量,如: int color = Color.BLUE;//创建一个蓝色 是使用An ...
- 关于在Java代码中写Sql语句需要注意的问题
最近做程序,时不时需要自己去手动将sql语句直接写入到Java代码中,写入sql语句时,需要注意几个小问题. 先看我之前写的几句简单的sql语句,自以为没有问题,但是编译直接报错. String st ...
随机推荐
- Label自适应高度
每次都逼我翻代码 这次干脆写博客里面算了 哈哈哈 CGSize maxSize = CGSizeMake(ScreenWith-30,NSIntegerMax); CGSize labelsize ...
- SVN 使用锁实现独占式签出
SVN默认并行工作,但是自动合并又做得很渣.团队工作中,如果确实有一些文件希望独占式签出可以使用SVN的特别属性. Subversion针对此问题的解决方案是提供一种机制,提醒用户在开 ...
- Mac OS X 删除文件快捷键
今天发现自己还不知道怎么快捷的删除文件,网上找了下相关的资料. 原来删除文件的快捷键是:command+delete(把文件放到废纸篓),对于我这种笔记本用户,确实方便很多哈 还有一个命令也挺有用的: ...
- 【好书摘要】性能优化中CPU、内存、磁盘IO、网络性能的依赖
系统优化是一项复杂.繁琐.长期的工作,优化前需要监测.采集.测试.评估,优化后也需要测试.采集.评估.监测,而且是一个长期和持续的过程,不 是说现在优化了,测试了,以后就可以一劳永逸了,也不是说书本上 ...
- 【转】JAVA 8 日期/时间(Date Time)API指南
前言 本来想写下Java 8的日期/时间API,发现已经有篇不错的文章了,那就直接转载吧~ PS:主要内容没变,做了部分修改. 原文链接: journaldev 翻译: ImportNew.com - ...
- Unknown tag
<c:forEach items="" var="" varStatus="s">缺少<%@ taglib uri=&qu ...
- SAM4E单片机之旅——24、使用DSP库求向量数量积
DSP(Digital Signal Processing,数字信号处理)中会使用大量的数学运算.Cortex-M4中,配置了一些强大的部件,以提高DSP能力.同时CMSIS提供了一个DSP库,提供了 ...
- Web Service 的工作原理
Web Service基本概念 Web Service也叫XML Web Service WebService是一种可以接收从Internet或者Intranet上的其它系统中传递过来的请求,轻量级的 ...
- linux pstack命令总结
pstack命令用来显示进程的栈跟踪. pstack 命令必须由相应进程的属主或root账号运行.可以使用pstack来确定进程挂起的位置.此命令只有一个参数,那就是pid,具体关于pstack的介绍 ...
- SQL Server 2012实施与管理实战指南(笔记)——Ch6连接的建立和问题排查
6.连接的建立和问题排查 会话的建立分成2个部分: 1.连接,即找到这个实例 2.认证,告诉sql server谁要连接 目录 6.连接的建立和问题排查 6.1协议选择和别名 6.1.1 服务器网络配 ...