我之前写了一篇文章讲了itext的基础操作常用方法(https://my.oschina.net/itazi/blog/1812042),但是有时涉及到比较复杂的PDF生成,手工操作就很复杂,可以使用模板生成方式。有时还要涉及合并等,于是将用到的略作记载。 首先要用到的依赖:

<dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.5.10</version>
</dependency><dependency><groupId>com.itextpdf</groupId><artifactId>itext-asian</artifactId><version>5.2.0</version>
</dependency><dependency><groupId>org.bouncycastle</groupId><artifactId>bcprov-jdk15on</artifactId><version>1.54</version>
</dependency><!-- https://mvnrepository.com/artifact/com.lowagie/itext -->
<dependency><groupId>com.lowagie</groupId><artifactId>itext</artifactId><version>2.1.7</version>
</dependency>

首先我们来讲讲制作模板,可以查考这个https://www.cnblogs.com/LUA123/p/5108007.html,这里面感觉很详细了,另外特别提到一点,由于要用Adobe制作的话需要购买,所以作为代替方案,你还可以使用福晰PDF软件制作,也可以实现相同效果,亲测可用。制作好模板之后接下来就是根据模板生成PDF,代码如下:

/*** 根据模版生成pdf* * @param templateFile 模板路径* @param targetFile 将要生成的pdf路径* @param fieldMap 填充字段*/
public static Boolean createPdfFromTemplate(String templateFile, String targetFile, Map<String, String> fieldMap) {Boolean retValue = false;try {/* 打开已经定义好字段以后的pdf模板 */com.itextpdf.text.pdf.PdfReader reader = new com.itextpdf.text.pdf.PdfReader(templateFile);/* 将要生成的目标PDF文件名称 */PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(targetFile));PdfContentByte under = stamp.getUnderContent(1);/* 使用中文字体 */BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H",BaseFont.NOT_EMBEDDED);Font fontChinese = new Font(bf, 12, Font.NORMAL);/* 取出报表模板中的所有字段 */AcroFields form = stamp.getAcroFields();form.addSubstitutionFont(bf);//这行必须添加否则中文不显示/* 为字段赋值,注意字段名称是区分大小写的 */for (String key : fieldMap.keySet()) {form.setField(key, fieldMap.get(key));}stamp.setFormFlattening(true);/* 必须要调用这个,否则文档不会生成的 */stamp.close();reader.close();retValue = true;} catch (DocumentException de) {System.err.println(de.getMessage());} catch (IOException ioe) {System.err.println(ioe.getMessage());} finally {return retValue;}}

测试代码如下(注意:关于路径你要改成你自己本地的路径,要正确,特别是你制作模板的路径,要填写正确,要不然模板都找不到,谈何制作pdf呢):

Map<String, String> map = new HashMap<String, String>();map.put("projectname", "map填充");//这里的projectname是你制作PDF时填入的字段map.put("applyname", "shishui??");//同上System.out.println(PdfUtils.createPdfFromTemplate("/Users/hxm/Documents/pdf/project_detail_model_wrapper_2.pdf", "/Users/hxm/Documents/pdf/tempalte.pdf", map));

结果: 填充成功。 接下来我们来谈谈合并PDF,有时候你有多个PDF,正好需要合并成一个,你可能就需要这个方法了(部分内容参考:https://www.cnblogs.com/pocketbook/p/6427579.html)。代码如下:

/*** 合并pdf* @param files 要合并的pdf文件* @param newfile 生成的文件名* @return*/
public static Boolean mergePdfFiles(String[] files, String newfile) {Boolean retValue = false;  Document document = null;  try {  document = new Document(new PdfReader(files[0]).getPageSize(1));PdfCopy copy = new PdfCopy(document, new FileOutputStream(newfile)); document.open();  for (int i = 0; i < files.length; i++) {  PdfReader reader = new PdfReader(files[i]);  int n = reader.getNumberOfPages();  for (int j = 1; j <= n; j++) {  document.newPage();  PdfImportedPage page = copy.getImportedPage(reader, j);  copy.addPage(page);  }  }  retValue = true;  } catch (Exception e) {  e.printStackTrace();  } finally {  document.close();  }  return retValue;
}  

测试代码(路径要能和你自己的pdf地址对上):

String[] files = { "/Users/hxm/Documents/pdf/audit.pdf", "/Users/hxm/Documents/pdf/template.pdf"};  String savepath = "/Users/hxm/Documents/pdf/newmerge"+ System.currentTimeMillis() +".pdf";  PdfTemplateUtil.mergePdfFiles(files, savepath);

结果: 合并成功。 如果已经存在一个PDF,你想添加某些属性再生成一个新的PDF文件,如增加水印,加密,设置权限等,这时你就又需要一个方法了,代码如下(其中部分参考一个外国小哥的代码):

public static Boolean addAttributeToPdfFile(String strFileLocation, String strFileLocationOut) {Boolean isSuccess = false;try {// read existing pdfcom.itextpdf.text.pdf.PdfReader reader = new com.itextpdf.text.pdf.PdfReader(strFileLocation);PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(strFileLocationOut));stamper.setEncryption(null, null, PdfWriter.ALLOW_PRINTING, PdfWriter.ENCRYPTION_AES_128);// text watermarkFont FONT = new Font(Font.FontFamily.HELVETICA, 34, Font.BOLD, new GrayColor(0.5f));
//            Phrase p = new Phrase("Memorynotfound (watermark)", FONT);BaseFont bfChinese = BaseFont.createFont("STSongStd-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);Font font = new Font(bfChinese, 30, Font.BOLD, new GrayColor(0.90f));Phrase p = new Phrase("(watermark)", font);// image watermark
//            Image img = Image.getInstance(imgUrl);
//            float w = img.getScaledWidth();
//            float h = img.getScaledHeight();// propertiesPdfContentByte over;Rectangle pagesize;float x, y;// loop over every pageint n = reader.getNumberOfPages();for (int i = 1; i <= n; i++) {// get page size and position
//                pagesize = reader.getPageSizeWithRotation(i);
//                x = (pagesize.getLeft() + pagesize.getRight()) / 2;
//                y = (pagesize.getTop() + pagesize.getBottom()) / 2;over = stamper.getUnderContent(i);over.saveState();// set transparencyPdfGState state = new PdfGState();state.setFillOpacity(0.2f);over.setGState(state);
//                ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, x, y, 0);//控制水印的显示效果,可以自己调整看看float beginPositionX = 10, beginPositionY = 70, distance = 175;for (int i2 = 0; i2 < 4; i2++) {for (int j = 0; j < 4; j++) {ColumnText.showTextAligned(over, Element.ALIGN_LEFT,p, beginPositionX + distance*i2, beginPositionY + distance*j, 25);}}// add watermark text and image
//                if (i % 2 == 1) {
//                    ColumnText.showTextAligned(over, Element.ALIGN_CENTER, p, x, y, 0);
//                } else {
//                    over.addImage(img, w, 0, 0, h, x - (w / 2), y - (h / 2));
//                }over.restoreState();}stamper.close();reader.close();isSuccess = true;} catch (DocumentException e) {// TODO Auto-generated catch blocke.printStackTrace();} catch (IOException e) {// TODO Auto-generated catch blocke.printStackTrace();} finally {return isSuccess;}
}

测试代码:

PdfUtils.addAttributeToPdfFile("/Users/hxm/Documents/pdf/newmerge1527731906780.pdf","/Users/hxm/Documents/pdf/mytemplate.pdf");

效果如下: 另外注意点是我上面的几个方法都放在一个叫PdfUtils的类中。大概结构如下:

package pdf;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import java.util.Map;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.ColumnText;
import com.itextpdf.text.pdf.GrayColor;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfGState;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
import com.lowagie.text.Document;
import com.lowagie.text.pdf.PdfCopy;
import com.lowagie.text.pdf.PdfImportedPage;
import com.lowagie.text.pdf.PdfReader;
/**
* pdf工具类
*
* @author hxm
*/
public class PdfUtils {
}

上面就是这些常用方法了,因为要用到本人也网上搜索了很多资料,看了很多,最后特地整理一下,也以备自己以后查询之用处。

转载于:https://my.oschina.net/itazi/blog/1822301

itext根据模版生成PDF与合并多个PDF以及向已存在PDF增加水印设置权限等操作相关推荐

  1. 办公自动化:PDF文件合并器,用Python将多个PDF文件进行合并

    相关文件 想学Python的小伙伴可以关注小编的公众号[Python日志] 有很多的资源可以白嫖的哈,不定时会更新一下Python的小知识的哈!! Python源码.问题解答学习交流群:7731621 ...

  2. Springboot——多个pdf文件合并成一个工具类编写

    文章目录 前言 实现 依赖引入 工具类编写 前言 最近接了一个需求,客户觉得一个合同导出多项类型的pdf数据,不够直接明了,需要将多个pdf文件 合并 成一个pdf. 实现 依赖引入 编写工具类之前, ...

  3. 将一个文件夹下的所有pdf文件合并为一个文件

    文章目录 1.将一个文件夹下的所有pdf文件合并为一个文件 这里还有一个 2.重新生成PDF文件 如题,每次都要重新写脚本很烦人,放在CSDN当做工具吧! 1.将一个文件夹下的所有pdf文件合并为一个 ...

  4. 手机怎么把几个PDF文件合并到一起?教你一分钟搞定

    怎么用手机把几个PDF文件合并到一起呢?大家在阅读浏览PDF文件的时候,如果收到别人发来的几个短小又精简的PDF文件时,浏览时就需要挨个打开,有时可能连打开的顺序都会弄混淆,十分影响我们阅读体验.那么 ...

  5. 多个PDF怎么合并?赶快看这篇文章学习一下

    相信大家在工作中或者学习中也都需要对文件进行处理,PDF文件就是经常处理的文件之一,我们经常需要将多个PDF进行合并,这样就可以减少文件数量,将同一类的文件合并到一个文件内,这样在我们寻找文件时就非常 ...

  6. 多个pdf怎么合并成一个pdf?教您几招快速合并的方法!

    多个pdf怎么合并成一个pdf?通常来说,将多个PDF文件进行合并是非常重要的.在我们日常工作中,我们经常需要使用PDF文件,比如合同.报告等.将多个相关的PDF文件合并成一个更大的文件可以方便我们查 ...

  7. Movavi PDFChef for Mac v22.2.0 PDF编辑合并转换工具

    Movavi PDFChef for Mac 是一个非常方便的编辑PDF的多功能程序.您可以添加和编辑文本,插入和调整图像大小.我们针对Mac OS的PDF编辑器还允许您重新排列.删除和旋转页面.使用 ...

  8. 多个pdf怎么合并在一起?

    多个pdf怎么合并在一起?身处职场的我们,每天都要面对和处理各种文件,其中使用率最高的非PDF文件莫属了.像小编每天都会处理二三十个大小不一的PDF文档.这些PDF文档要是对一个新手而言,我想必然会闹 ...

  9. 不花钱的pdf编辑器_PDF补丁丁,一款能修改PDF的插件,只有8M~

    下载软件你的3位好友已关注 下载 公众号:[下载软件]内回复[143]获取下载链接 软件介绍 分享一款优秀的PDF小工具,压缩包8M首先这个名字很搞笑啊,这是不满 PDF,然后给它打了补丁,最后可能觉 ...

最新文章

  1. 03 基本数据类型、运算符 输入输出
  2. Openresty最佳案例 | 第3篇:Openresty的安装
  3. 信用模型评分卡入门介绍
  4. 【Detectron2】使用 Detectron2 训练基于 coco 数据集的目标检测网络
  5. python获取mysql中的数据供js调用_详解js文件通过python访问数据库方法
  6. 一款简洁大气的商城官网介绍源码
  7. AngularJS日期格式化
  8. REDO LOG大小引起的Oracle数据库性能下降
  9. 一个命令让redis服务端所有信息无所遁形~(收藏吃灰系列)
  10. next.js 安装简易教程
  11. Jenkins小坑之执行Shell
  12. 计算机网络的DIX,《计算机网络》期末考试试卷(B卷)
  13. python科赫曲线编程实现雪花下落的效果_基于python绘制科赫雪花
  14. html给字体设置大小,如何设置html字体大小
  15. 白天黑夜、中午和傍晚的固定配色绘画技巧
  16. mac php pear pecl,MacOSX安装pecl - 米扑博客
  17. 嵌入式linux/鸿蒙开发板(IMX6ULL)开发(一) 嵌入式Linux开发基本概念以及开发流程介绍
  18. 专硕计算机学院排名,考研计算机院校排名
  19. FTP服务器获取文件,并解析GRB2文件获取数据
  20. hive--union all后无数据/少数据

热门文章

  1. ACSI: 360度无死角测量顾客满意度
  2. 挂起的更改中的“解析”是什么意思?原来是微软错误的翻译
  3. Windows Server 2008 系统加固
  4. cs1.5服务器指定ip,求上海地区cs1.5服务器IP
  5. 帆软报表填报导入excel数据出现错误
  6. 著名密码破解利器John the Ripper使用方法详解
  7. 转 OKapi BM25 算法
  8. excel 拼接单引号
  9. 实验一:网络扫描与网络侦查
  10. 【域名防红】QQ与微信标红查询接口