java根据pdf模版动态生成pdf

package com.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry; import org.apache.commons.io.FileUtils;
import org.xhtmlrenderer.pdf.ITextFontResolver;
import org.xhtmlrenderer.pdf.ITextRenderer; import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Element;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Phrase;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.AcroFields.Item;
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.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter; /**
* 根据pdf模版动态生成pdf工具类
*/
public class PDFReplaceUtils { public static final String htmlPreffix = "<!DOCTYPE html [<!ENTITY nbsp \" \"> ]><html><head><meta charset=\"UTF-8\"></meta><title></title></head><body>";
public static final String htmlSuffix = "</body></html>" ; /**
* 动态生成pdf
*
* @
* @date 2017年11月5日 上午11:40:44
* @param fileName
* 模版路径
* @param outFileName
* 生成pdf路径
* @param map
* 动态赋值pdf文本域名称和值
* @throws IOException
* @throws DocumentException
*/
public static void pdf(String fileName, String outFileName, Map<String, String> map)
throws IOException, DocumentException {
PdfReader reader = new PdfReader(fileName);
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PdfStamper ps = new PdfStamper(reader, bos);
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
ArrayList<BaseFont> fontList = new ArrayList<BaseFont>();
fontList.add(bf); AcroFields s = ps.getAcroFields();
s.setSubstitutionFonts(fontList);
Map<String, Item> fieldMap = s.getFields(); // pdf表单相关信息展示
for (Entry<String, Item> entry : fieldMap.entrySet()) {
String name = entry.getKey(); // name就是pdf模版中各个文本域的名字
Item item = entry.getValue();
}
// 给pdf文本域赋值
for (Entry<String, String> maps : map.entrySet()) {
s.setField(maps.getKey(), maps.getValue());
}
ps.setFormFlattening(true); // 不能少
ps.close(); OutputStream fos = new FileOutputStream(outFileName);
fos.write(bos.toByteArray());
fos.flush();
fos.close();
bos.close();
reader.close();
} /**
* 创建pdf表格
*
* @
* @date 2017年11月5日 下午8:48:07
* @param fileName
* 表格名称
* @param columnNum
* 列数
* @param lists
* 单元格内容
* @throws DocumentException
* @throws IOException
*/
public static void createPdfTable(String fileName, int columnNum, List<Map<String, String>> lists)
throws DocumentException, IOException {
Document document = new Document(PageSize.A4); PdfWriter.getInstance(document, new FileOutputStream(fileName));
document.open(); PdfPTable table = new PdfPTable(columnNum);
table.setTotalWidth(50);
table.setHeaderRows(0);
table.setSpacingBefore(10f);
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
Font chinese = new Font(bf, 12, Font.NORMAL);
Phrase phrase;
PdfPCell cell;
for (Map<String, String> map : lists) {
for (Entry<String, String> maps : map.entrySet()) {
phrase = new Phrase(maps.getValue(), chinese);
cell = new PdfPCell(phrase);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.addCell(cell);
}
}
document.add(table);
document.close();
} /**
* 多个pdf合并,根据参数选择是否删除参与合并的pdf、 将合并后的pdf名称改为第几个参与合并的名称 注:需参与合并的pdf文件 请按需求正序排序
*
* @
* @date 2017年11月7日 下午8:46:43
* @param fileList
* 要合并的pdf集合
* @param newFile
* 新文件
* @param isDelete
* 是否删除参与合并的pdf文件
* @param numFileName
* 将新pdf文件名改为 第几个 参与合并pdf名
* @throws DocumentException
* @throws IOException
*/
public static void mergePdfFiles(List<String> fileList, String newFile, Boolean isDelete, Integer numFileName)
throws DocumentException, IOException {
PdfReader[] readers = new PdfReader[fileList.size()];
readers[0] = new PdfReader(fileList.get(0));
PdfStamper stamp = new PdfStamper(readers[0], new FileOutputStream(newFile));
PdfContentByte under;
int pageNum = 1;
for (int i = 1; i < fileList.size(); i++) {
readers[i] = new PdfReader(fileList.get(i), null);
pageNum += readers[i].getNumberOfPages();
stamp.insertPage(pageNum, PageSize.A4);
under = stamp.getUnderContent(pageNum);
under.addTemplate(stamp.getImportedPage(readers[i], 1), 1, 0, 0, 1, 0, 0);
}
stamp.close();
for (PdfReader pdfReader : readers) {
pdfReader.close();
} if (isDelete != null && isDelete == true) {
// 循环删除文件
for (String file : fileList) {
new File(file).delete();
}
} if (numFileName != null && numFileName > 0) {
// 将新文件名改为第N个文件的路径
File modifyFileName = new File(newFile);
modifyFileName.renameTo(new File(fileList.get(numFileName - 1)));
}
} /**
* 富文本生成pdf文件
*
* @param context
* html格式文本数据
* @param outputFile
* 输出pdf文件的路径
* @return
* @throws Exception
*/
public static boolean convertHtmlToPdf(String context, String outputFile,String fontPath) throws Exception { OutputStream os = new FileOutputStream(outputFile);
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(context); // 解决中文支持问题
ITextFontResolver fontResolver = renderer.getFontResolver();
fontResolver.addFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
// 解决图片的相对路径问题
// renderer.getSharedContext().setBaseURL("file:/D:/");
renderer.layout();
renderer.createPDF(os); os.flush();
os.close();
return true;
} public static void main(String[] args) throws IOException, DocumentException {
// List<String> list = new LinkedList<String>();
// list.add("D:/1.pdf");
// list.add("D:/2.pdf");
// list.add("D:/3.pdf");
// String newFile = "D:/4.pdf";
// try {
// PDFReplaceUtils.mergePdfFiles(list, newFile, true, 2);
// } catch (DocumentException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } byte[] bytes;
try {
// bytes = FileUtils.readFileToByteArray(new File("D:/pdftest.html"));
// convertHtmlToPdf(new String(bytes),"D:/lc.pdf","D:/simsun.ttc");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
} Map<String, String> map = new HashMap<String, String>();
map.put("ProtocolNo", "jj");
map.put("Borrower", "qq");
map.put("Mobile", "12345678912");
pdf("D:/jcsBorrow.pdf", "D:/test.pdf", map); // try {
// List<Map<String, String>> list = null;
// Map<String, String> map = new HashMap<String, String>();
// list = new LinkedList<Map<String, String>>();
// map.put("出借人(会员号)", "出借人(会员号)");
// map.put("出借人身份证号", "出借人身份证号");
// map.put("出借金额", "出借金额");
// map.put("借款开始日", "借款开始日");
// map.put("月截止还款日", "月截止还款日");
// map.put("年利率", "年利率");
// map.put("还款方式", "还款方式");
// list.add(map);
// createPdfTable("D:/test.pdf", 7, list);
// } catch (DocumentException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// } catch (IOException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
}
}

java根据pdf模版动态生成pdf的更多相关文章

  1. java根据模板HTML动态生成PDF

    原文:https://segmentfault.com/a/1190000009160184 一.需求说明:根据业务需要,需要在服务器端生成可动态配置的PDF文档,方便数据可视化查看. 二.解决方案: ...

  2. 利用Java动态生成 PDF 文档

    利用Java动态生成 PDF 文档,则需要开源的API.首先我们先想象需求,在企业应用中,客户会提出一些复杂的需求,比如会针对具体的业务,构建比较典型的具备文档性质的内容,一般会导出PDF进行存档.那 ...

  3. Java 动态生成 PDF 文件

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

  4. Asp.net MVC Razor视图模版动态渲染PDF,Razor模版生成静态Html

    Asp.net MVC Razor视图模版动态渲染PDF,Razor模版生成静态Html 1.前言 上一篇文章我开源了轮子,Asp.net Core 3.1 Razor视图模版动态渲染PDF,然后,很 ...

  5. Asp.net Core 3.1 Razor视图模版动态渲染PDF

    Asp.net Core 3.1 Razor视图模版动态渲染PDF 前言 最近的线上项目受理回执接入了电子签章,老项目一直是html打印,但是接入的电子签章是仅仅对PDF电子签章,目前还没有Html电 ...

  6. django生成文件txt、pdf(在生成 PDF 文件之前,需要安装 ReportLab 库)

    from django.http import HttpResponse def download_file(request): # Text file #response = HttpRespons ...

  7. django 动态生成PDF文件

    可以通过开源的Python PDF库ReportLab来实现PDF文件的动态生成. 一.安装ReportLab ReportLab库在PyPI上提供,可以使用pip来安装: $ pip install ...

  8. JAVA使用itext根据模板生成PDF文档

    1.制作PDF模板 网址打开:https://www.pdfescape.com/open/ 我们这里先在线上把基础的内容用word文档做好,然后转成PDF模板,直接上传到网站上,这样方便点 假设我们 ...

  9. 第二章:视图层 - 10:动态生成PDF文件

    可以通过开源的Python PDF库ReportLab来实现PDF文件的动态生成. 一.安装ReportLab ReportLab库在PyPI上提供,可以使用pip来安装: $ pip install ...

随机推荐

  1. Split功能的思想实现

    using System; using System.Collections; using System.Collections.Generic; using System.Linq; using S ...

  2. Linux运维-Rsync+Inotify

      Rsync+Inotify Rsync:linux系统下的数据镜像备份工具.使用快速增量备份工具Remote Sync可以远程同步,支持本地复制,或者与其他SSH.rsync主机同步. 特性: 可 ...

  3. iOS9的新特性以及适配方案-----转载

    2015年9月8日,苹果宣布iOS 9操作系统的正式版在太平洋时间9月16日正式推出,北京时间9月17日凌晨1点推送. 新的iOS 9系统比iOS8更稳定,功能更全面,而且还更加开放.iOS 9加入了 ...

  4. Vue Devtools--vue调式工具

    当浏览器控制台出现:Download the Vue Devtools extension for a better development experience: 1:安装 地址:https://g ...

  5. I.MX6 Linux eGTouch TouchScreen porting

    I.MX6 Linux eGTouch TouchScreen porting 一.Download Driver: http://www.eeti.com.tw/drivers_Linux.html ...

  6. laravel 修改重置密码模板

    Laravel里我们可以使用php artisan make:auth来生成一套默认的登陆注册重置邮箱的Authentication System,但是如何修改系统发送给用户的重置密码邮件的样式和内容 ...

  7. ffpmeg下rtmp踩坑记录

    1. flash端发布直播流 2.在 ffplay 命令行中 播放rtmp 直播流 ffplay "rtmp://127.0.0.1:80/live/ss live=1"  一直出 ...

  8. Android HOOK工具Cydia Substrate使用详解

    目录(?)[+] Substrate几个重要API介绍 MShookClassLoad MShookMethod 使用方法 短信监控实例   Cydia Substrate是一个代码修改平台.它可以修 ...

  9. win10/ubuntu双系统卸载删除ubuntu系统

    1.重启进入boot-设置windows启动项为首选项. 2.删除EFI中ubuntu引导启动项: a.将EFI分区挂载到M盘->(管理员权限)命令行输入:mountvol M: /s b.进入 ...

  10. .NET Standard / dotnet-core / net472 —— .NET 究竟应该如何大小写?

    本文将解释在 .NET 技术栈中各种不同使用方式下 N E T 三个字母何时大写何时小写:前面的 “.” 什么时候加上,什么时候去掉,什么时候又使用 “dot”.   .NET 在技术文档中 如果你阅 ...