利用模板将json转PDF并保存下载

更新时间:2023-08-01 22:23:44 阅读: 评论:0

利⽤模板将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();
ps调整颜色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);

本文发布于:2023-08-01 22:23:44,感谢您对本站的认可!

本文链接:https://www.wtabcd.cn/fanwen/fan/82/1126148.html

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。

标签:模板   表单   操作   编辑   修改
相关文章
留言与评论(共有 0 条评论)
   
验证码:
推荐文章
排行榜
Copyright ©2019-2022 Comsenz Inc.Powered by © 专利检索| 网站地图