利⽤模板将json转PDF并保存下载
maven依赖
<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>
基础操作
itext有很多功能,这⾥先说基本的操作。其他更多⾼级的操作,可以继续看下⾯的。
基本处理步骤如下伪代码:
//Step 1—Create a Document.
Document document = new Document();
//Step 2—Get a PdfWriter instance.
//Step 3—Open the Document.
document.open();
//Step 4—Add content.
document.add(new Paragraph("Hello World"));
//Step 5—Clo the Document.
document.clo();
1、直接输出数据到pdf⽂件
这⾥有个特别注意的是,中⽂必须要指定字体,即是BaFont
public class PDFReport {
private final static String REPORT_PATH = "C:/air-navi-monitor/report";
private static void exportReport() {
BaFont bf;
Font font = null;
Font font2 = null;
有信用
try {
bf = ateFont("STSong-Light", "UniGB-UCS2-H",
BaFont.NOT_EMBEDDED);//创建字体
font = new Font(bf, 12);//使⽤字体
font2 = new Font(bf, 12, Font.BOLD);//使⽤字体
} catch (Exception e) {
e.printStackTrace();
}
Document document = new Document();
try {
document.open();
Paragraph elements = new Paragraph("常州武进1区飞⾏报告", font2);
elements.tAlignment(Paragraph.ALIGN_CENTER);
document.add(elements);
Image png = Instance("E:\\test.png");
png.tAlignment(Image.ALIGN_CENTER);
document.add(png);
document.add(new Paragraph("任务编号:20190701 开始⽇期:20190701", font));
document.add(new Paragraph("任务名称:常州武进1区结束⽇期:20190701", font));
document.add(new Paragraph("平均飞⾏⾼度:100m 平均飞⾏速度:100km/h", font));
document.add(new Paragraph("任务⾯积:1000㎡结束⽇期:20190701", font));
document.add(new Paragraph("飞⾏总时长:1000㎡", font));
document.addCreationDate();
document.clo();
} catch (Exception e) {
System.out.println("file create exception");
}
}
/**
* ⽣成pdf⽂件
*
* @param missionReport
* @return
*/
public static String exportReport(MissionReportTb missionReport) throws AirNaviException {
String pdfPath = null;
String imgPath = MissionID());
// String imgPath = "E:\\test.png";
String finalReportStr = MissionReport();
MissionReport finalReport = JSONObject.parObject(finalReportStr, MissionReport.class);
BaFont bf;
Font font = null;
Font font2 = null;
try {
bf = ateFont("STSong-Light", "UniGB-UCS2-H",
BaFont.NOT_EMBEDDED);//创建字体
font = new Font(bf, 12);//使⽤字体
font2 = new Font(bf, 12, Font.BOLD);//使⽤字体
} catch (Exception e) {
e.printStackTrace();
}
Document document = new Document();
try {
File dir = new File(REPORT_PATH);
if (!ists()) {
dir.mkdirs();
}
File file = new File(REPORT_PATH + File.parator + MissionID() + ".pdf");
if (!ists()) {
}
document.open();
Paragraph elements = new MissionName() + "飞⾏报告", font2);
elements.tAlignment(Paragraph.ALIGN_CENTER);
document.add(elements);
Image png = Instance(imgPath);
// blog.csdn/lingbo89/article/details/76177825
float documentWidth = PageSize().getWidth() - document.leftMargin() - document.rightMargin();
float documentHeight = documentWidth / 580 * 320;//重新设置宽⾼
png.scaleAbsolute(documentWidth, documentHeight);//重新设置宽⾼
png.scalePercent(50);
// 根据域的⼤⼩缩放图⽚
// image.Width(), Height());
png.tAlignment(Image.ALIGN_CENTER);
document.add(png);
document.add(new Paragraph("任务编号:" + MissionCode() + ",开始⽇期:" + StartTime(), font));
document.add(new Paragraph("任务名称:" + MissionName() + ",结束⽇期:" + EndTime(), font));
document.add(new Paragraph("平均飞⾏⾼度:" + AvgFlightHeight() + "m" + ",平均飞⾏速度:" + AvgFlightSpeed() + "km/h", font)); document.add(new Paragraph("任务⾯积:" + MissionArea() + "㎡" + ",飞⾏总时长:" + FlightDuration() + "min", font));
document.addCreationDate();
document.clo();
pdfPath = AbsolutePath();
} catch (Exception e) {
汉字的由来e.printStackTrace();
<(e.getMessage());
System.out.println("file create exception");
throw new AirNaviException("⽣成PDF失败:" + e.getMessage());
}
return pdfPath;
}
public static void main(String[] args) throws AirNaviException {
String report = "{\"detailMissionReport\":[{\"avgFlightHeight\":119.7,\"avgFlightSpeed\":71.1,\"endPoint\":\"113.27484,22.86843\",\"endTime\":\"2019-09-17 17:47:07\",\"flightDuration\":9,\"reportID\":1,\"startPoint\":\"113.31429,22.78240\",\"startTime\":\"2019-09-17 MissionReportTb missionReportTb = JSONObject.parObject(report, MissionReportTb.class);
exportReport(missionReportTb);
}
}
2、根据模板⽣成pdf⽂件并导出
⾸先你的制作⼀个pdf模板:
1.先⽤word做出模板界⾯
2.⽂件另存为pdf格式⽂件
4.点击右边的"准备表单"按钮,选择"测试.pdf"选择开始
进去到编辑页⾯,打开后它会⾃动侦测并命名表单域,右键表单域,点击属性,出现⽂本域属性对话框(其实⽆需任何操作,⼀般情况下不需要修改什么东西,⾄少我没有修改哦。如果你想修改fill1等信息,可以进⾏修改)
5.做完上⾯的⼯作后,直接"另存为"将pdf存储就可以
以上部分是制作pdf模板操作,上述完成后,就开始通过程序来根据pdf模板⽣成pdf⽂件了,上java程序:
public class Snippet {
// 利⽤模板⽣成pdf
public static void fillTemplate() {
// 模板路径
String templatePath = "E:/测试3.pdf";
// ⽣成的新⽂件路径
String newPDFPath = "E:/ceshi.pdf";
PdfReader reader;
FileOutputStream out;
ByteArrayOutputStream bos;
PdfStamper stamper;
try {
out = new FileOutputStream(newPDFPath);// 输出流
reader = new PdfReader(templatePath);// 读取pdf模板
bos = new ByteArrayOutputStream();
stamper = new PdfStamper(reader, bos);
AcroFields form = AcroFields();
String[] str = {"123456789", "TOP__ONE", "男", "1991-01-01", "130222111133338888", "河北省保定市"};
int i = 0;
java.util.Iterator<String> it = Fields().keySet().iterator();
while (it.hasNext()) {
String name = it.next().toString();
System.out.println(name);
form.tField(name, str[i++]);
}
stamper.tFormFlattening(true);// 如果为fal那么⽣成的PDF⽂件还能编辑,⼀定要设为true
stamper.clo();
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, out);
doc.open();
PdfImportedPage importPage = ImportedPage(new ByteArray()), 1);
copy.addPage(importPage);
doc.clo();
} catch (IOException e) {
System.out.println(1);
} catch (DocumentException e) {
System.out.println(2);
}
}
public static void main(String[] args) {
fillTemplate();
}
}
运⾏结果如下
更多操作
1、页⾯⼤⼩,页⾯背景⾊,页边空⽩,Title,Author,Subject,Keywords
核⼼代码:
//页⾯⼤⼩
Rectangle rect = new Rectangle(ate());
//页⾯背景⾊
rect.tBackgroundColor(BaColor.ORANGE);
Document doc = new Document(rect);
PdfWriter writer = Instance(doc, out);
最高法院长//PDF版本(默认1.4)
writer.tPdfVersion(PdfWriter.PDF_VERSION_1_2);
//⽂档属性
doc.addTitle("Title@sample");
doc.addAuthor("Author@rensanning");
doc.addSubject("Subject@iText sample");
doc.addKeywords("Keywords@iText");
doc.addCreator("Creator@iText");
//页边空⽩
doc.tMargins(10, 20, 30, 40);
doc.open();
doc.add(new Paragraph("Hello World"));
输出结果:
2、设置密码
核⼼代码:
PdfWriter writer = Instance(doc, out);
// 设置密码为:"World"
writer.tEncryption("Hello".getBytes(), "World".getBytes(),
PdfWriter.ALLOW_SCREENREADERS,
PdfWriter.STANDARD_ENCRYPTION_128);
doc.open();
doc.add(new Paragraph("Hello World"));
输出结果:
3、添加Page
核⼼代码:
document.open();
document.add(new Paragraph("First page"));
document.add(new Version()));
writer.tPageEmpty(fal);
document.add(new Paragraph("New page"));
4、添加⽔印(背景图)
//图⽚⽔印
PdfReader reader = new PdfReader(FILE_DIR + "tWatermark.pdf");
PdfStamper stamp = new PdfStamper(reader, new FileOutputStream(FILE_DIR
+ "tWatermark2.pdf"));
Image img = Instance("resource/watermark.jpg");
img.tAbsolutePosition(200, 400);
PdfContentByte under = UnderContent(1);
under.addImage(img);
//⽂字⽔印
PdfContentByte over = OverContent(2);
鼠标悬停事件over.beginText();
BaFont bf = ateFont(BaFont.HELVETICA, BaFont.WINANSI,
BaFont.EMBEDDED);
over.tFontAndSize(bf, 18);
over.tTextMatrix(30, 30);
over.showTextAligned(Element.ALIGN_LEFT, "DUPLICATE", 230, 430, 45);
//背景图
Image img2 = Instance("resource/test.jpg");
img2.tAbsolutePosition(0, 0);
PdfContentByte under2 = UnderContent(3);
under2.addImage(img2);
stamp.clo();
reader.clo();
5、插⼊Chunk, Phra, Paragraph, List
核⼼代码
//Chunk对象: a String, a Font, and some attributes
document.add(new Chunk("China"));
document.add(new Chunk(" "));
Font font = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaColor.WHITE); Chunk id = new Chunk("chine", font);
id.tBackground(BaColor.BLACK, 1f, 0.5f, 1f, 1.5f);
id.tTextRi(6);
document.add(id);
document.add(Chunk.NEWLINE);
document.add(new Chunk("Japan"));
公司目标怎么写
document.add(new Chunk(" "));
Font font2 = new Font(Font.FontFamily.HELVETICA, 6, Font.BOLD, BaColor.WHITE); Chunk id2 = new Chunk("japane", font2);
id2.tBackground(BaColor.BLACK, 1f, 0.5f, 1f, 1.5f);
id2.tTextRi(6);
id2.tUnderline(0.2f, -2f);
document.add(id2);
document.add(Chunk.NEWLINE);
//Phra对象: a List of Chunks with leading
document.add(new Phra("Phra page"));
Phra director = new Phra();
Chunk name = new Chunk("China");
name.tUnderline(0.2f, -2f);
director.add(name);
director.add(new Chunk(","));
director.add(new Chunk(" "));
director.add(new Chunk("chine"));
director.tLeading(24);
document.add(director);
Phra director2 = new Phra();
Chunk name2 = new Chunk("Japan");
name2.tUnderline(0.2f, -2f);
director2.add(name2);
director2.add(new Chunk(","));
director2.add(new Chunk(" "));
director2.add(new Chunk("japane"));
director2.tLeading(24);
document.add(director2);
梦想天空分外蓝
//Paragraph对象: a Phra with extra properties and a newline
document.add(new Paragraph("Paragraph page"));
Paragraph info = new Paragraph();
info.add(new Chunk("China "));
info.add(new Chunk("chine"));
info.add(Chunk.NEWLINE);
info.add(new Phra("Japan "));
治疗肝病的药info.add(new Phra("japane"));
document.add(info);
//List对象: a quence of Paragraphs called ListItem
List list = new List(List.ORDERED);
for (int i = 0; i < 10; i++) {
ListItem item = new ListItem(String.format("%s: %d movies",
"country" + (i + 1), (i + 1) * 100), new Font(
Font.FontFamily.HELVETICA, 6, Font.BOLD, BaColor.WHITE));
List movielist = new List(List.ORDERED, List.ALPHABETICAL);
movielist.tLowerca(List.LOWERCASE);
for (int j = 0; j < 5; j++) {
ListItem movieitem = new ListItem("Title" + (j + 1));
List directorlist = new List(List.UNORDERED);
for (int k = 0; k < 3; k++) {
directorlist.add(String.format("%s, %s", "Name1" + (k + 1),
"Name2" + (k + 1)));
}
movieitem.add(directorlist);
movielist.add(movieitem);
}
item.add(movielist);
list.add(item);
学做湘菜}
document.add(list);
6、插⼊表格
PdfPTable table = new PdfPTable(3);
PdfPCell cell;
cell = new PdfPCell(new Phra("Cell with colspan 3"));
cell.tColspan(3);
table.addCell(cell);
cell = new PdfPCell(new Phra("Cell with rowspan 2"));
cell.tRowspan(2);
table.addCell(cell);
table.addCell("row 1; cell 1");
table.addCell("row 1; cell 2");
table.addCell("row 2; cell 1");
table.addCell("row 2; cell 2");
7、表格嵌套
PdfPTable table = new PdfPTable(4);
//1⾏2列
PdfPTable nested1 = new PdfPTable(2);
nested1.addCell("1.1");
nested1.addCell("1.2");
//2⾏1列
PdfPTable nested2 = new PdfPTable(1);
nested2.addCell("2.1");
nested2.addCell("2.2");
//将表格插⼊到指定位置
for (int k = 0; k < 24; ++k) {
if (k == 1) {
table.addCell(nested1);
} el if (k == 20) {
table.addCell(nested2);
} el {
table.addCell("cell " + k);
}
}
document.add(table);
8、设置表头
String[] bogusData = { "M0065920", "SL", "FR86000P", "PCGOLD",
"119000", "96 06", "2001-08-13", "4350", "6011648299",
"FLFLMTGP", "153", "119000.00" };
int NumColumns = 12;
// 12
PdfPTable datatable = new PdfPTable(NumColumns);
int headerwidths[] = { 9, 4, 8, 10, 8, 11, 9, 7, 9, 10, 4, 10 }; // percentage
datatable.tWidths(headerwidths);
datatable.tWidthPercentage(100);
datatable.addCell("Clock #");
datatable.addCell("Trans Type");
datatable.addCell("Cusip");
datatable.addCell("Long Name");
datatable.addCell("Quantity");
datatable.addCell("Fraction Price");
datatable.addCell("Settle Date");
datatable.addCell("Portfolio");
datatable.addCell("ADP Number");
datatable.addCell("Account ID");
datatable.addCell("Reg Rep ID");
datatable.addCell("Amt To Go ");
datatable.tHeaderRows(1);
/
/边框
//背景⾊
for (int i = 1; i < 1000; i++) {
for (int x = 0; x < NumColumns; x++) {
datatable.addCell(bogusData[x]);
}
}
document.add(datatable);
中⽂显⽰不全应对⽅法
// 提取PDF中的表单
AcroFields form = AcroFields();
// 设置中⽂字体
BaFont baFont = ateFont("STSongStd-Light", "UniGB-UCS2-H", BaFont.NOT_EMBEDDED); form.addSubstitutionFont(baFont);