依赖
<!-- https://mvnrepository.com/artifact/com.itextpdf/itextpdf -->
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency>
工具类
package org.jeecg.utils;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayOutputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.util.*;
import java.util.List;
public class PDFUtil {
/**
* pdf模板导出
*
* @param map 导出结果
* @param filePath 空pdf路径,作物前端访问路径
* @throws Exception
*/
public static void creatPdf(Map<String, Object> map, String filePath) throws Exception {
try {
FileOutputStream fos = new FileOutputStream(filePath);;
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
// 读取pdf模板路径
Resource resource = new ClassPathResource(String.valueOf(map.get("tempPath")));
PdfReader reader = new PdfReader(resource.getURL());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(reader, bos);
stamper.setFormFlattening(true);
AcroFields form = stamper.getAcroFields();
// 文字类的内容处理
Map<String, String> datemap = (Map<String, String>) map.get("dataMap");
form.addSubstitutionFont(bf);
for (String key : datemap.keySet()) {
String value = datemap.get(key);
form.setField(key, value);
form.setFieldProperty(key,"textsize",9f,null);
}
// 图片类的内容处理
Map<String, String> imgmap = (Map<String, String>) map.get("imgMap");
for (String key : imgmap.keySet()) {
String value = imgmap.get(key);
String imgpath = value;
int pageNo = form.getFieldPositions(key).get(0).page;
Rectangle signRect = form.getFieldPositions(key).get(0).position;
float x = signRect.getLeft();
float y = signRect.getBottom();
// 根据路径读取图片
Image image = Image.getInstance(imgpath);
// 获取图片页面
PdfContentByte under = stamper.getOverContent(pageNo);
// 图片大小自适应
image.scaleToFit(signRect.getWidth(), signRect.getHeight());
// 添加图片
image.setAbsolutePosition(x, y);
under.addImage(image);
}
// 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑
stamper.setFormFlattening(false);
stamper.close();
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, fos);
doc.open();
int pageNum = reader.getNumberOfPages();
for (int i = 1; i <= pageNum; i++) {
PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
copy.addPage(importPage);
}
doc.close();
fos.close();
} catch (IOException e) {
System.out.println(e);
} catch (DocumentException e) {
System.out.println(e);
}
}
}
导出结果数据实例(仅供参考)
package com.fiftheconomic.dataCalculate.service.impl;
import com.fiftheconomic.dataCalculate.domain.TjDataCalculateBase;
import com.fiftheconomic.dataCalculate.domain.TjDataCalculateDetail;
import com.fiftheconomic.dataCalculate.domain.resCompenyIndex;
import com.fiftheconomic.dataCalculate.service.IPdfService;
import org.springframework.stereotype.Service;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.util.*;
/**
* @Author: 苏子龙
* @Date: 2023/08/01/17:00
* @Description:
*/
@Service
public class PdfServiceImpl implements IPdfService {
/**
* 123 工业单位填报 124 批发和零售业单位填报 125 住宿和餐饮业单位填报 126 制造业,信息传输、软件和信息技术服务业,科学研究和技术服务业单位填报
*
* @param resMap
* @param list
* @return
*/
@Override
public Map<String, Object> oneThree(List<resCompenyIndex> resMap, TjDataCalculateBase base, List<TjDataCalculateDetail> list) {
List<List<String>> lists = new ArrayList<>();//表格 (一行数据一个list)
SimpleDateFormat dft = new SimpleDateFormat("yyyy-MM-dd");
Map<String, String> map = new HashMap<>();//文本域
for (int i = 0; i < resMap.size(); i++) {
if (resMap.get(i).getIndexCode() != null) {
if (!map.containsKey(resMap.get(i).getIndexCode())) {
map.put(resMap.get(i).getIndexCode(), resMap.get(i).getIndexValue());
}
}
}
//添加tj_data_calculate_index基础信息表数据
for (int j = 0; j < list.size(); j++) {
System.out.println("++++++++" + j);
TjDataCalculateDetail data = list.get(j);
map.put("name" + j, data.getIndexName());
map.put("unit" + j, data.getUnitof());
map.put("value" + j, data.getIndexValue());
}
// map.put("name", "无"); //添加tj_data_calculate_index头信息
// map.put("nameInfo", "无"); //填表人姓名
// map.put("phoen", "无");//填表人电话
// map.put("nameBy", "无");//单位负责人
// map.put("USCI", base.getUSCI());//企业社会信用统一代码
// map.put("comName", base.getComName());//单位详细名称
// //添加日期
// LocalDate now = LocalDate.now();
// map.put("y", String.valueOf(now.getYear()));
// map.put("m", String.valueOf(now.getMonthValue()));
// map.put("d", String.valueOf(now.getDayOfMonth()));
// map.put("time", String.valueOf(now));//填表人电话
Map<String, Object> o = new HashMap<>();
String s = base.getIndustryCode();
if (s.equals("1")) {
o.put("tempPath", "static/pdf/123.pdf");
} else if (s.equals("2") || s.equals("3")) {
o.put("tempPath", "static/pdf/124.pdf");
} else if (s.equals("4") || s.equals("5")) {
o.put("tempPath", "static/pdf/125.pdf");
} else {
o.put("tempPath", "static/pdf/126.pdf");
}
o.put("dataMap", map);
o.put("imgMap", new HashMap<>());
Map<String, List<List<String>>> listMap = new HashMap<>();
listMap.put("table", lists);
o.put("tableList", listMap);
return o;
}
public static void main(String[] args) {
LocalDate now = LocalDate.now();
System.out.println(now.getYear());
System.out.println(now.getMonthValue());
System.out.println(now.getDayOfMonth());
}
}
优化工具包
public static String creatPdf1(Map<String, Object> map ,OutputStream out,float width[]) throws Exception {
BaseFont bf = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
// // 输出流
// String outPutPath = "E:/excel/files/pdf模板导出.pdf";
// FileOutputStream out = new FileOutputStream(filePath);
// 读取pdf模板路径
Resource resource = new ClassPathResource(String.valueOf(map.get("tempPath")));
PdfReader reader = new PdfReader(resource.getURL());
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PdfStamper stamper = new PdfStamper(reader, bos);
stamper.setFormFlattening(true);
AcroFields form = stamper.getAcroFields();
// 文字类的内容处理
Map<String, String> datemap = (Map<String, String>) map.get("dataMap");
form.addSubstitutionFont(bf);
for (String key : datemap.keySet()) {
String value = datemap.get(key);
form.setField(key, value);
form.setFieldProperty(key, "textsize", 9f, null);
}
// 图片类的内容处理
Map<String, String> imgmap = (Map<String, String>) map.get("imgMap");
for (String key : imgmap.keySet()) {
String value = imgmap.get(key);
String imgpath = value;
int pageNo = form.getFieldPositions(key).get(0).page;
Rectangle signRect = form.getFieldPositions(key).get(0).position;
float x = signRect.getLeft();
float y = signRect.getBottom();
// 根据路径读取图片
Image image = Image.getInstance(imgpath);
// 获取图片页面
PdfContentByte under = stamper.getOverContent(pageNo);
// 图片大小自适应
image.scaleToFit(signRect.getWidth(), signRect.getHeight());
// 添加图片
image.setAbsolutePosition(x, y);
under.addImage(image);
}
// 表格类
Map<String, List<List<String>>> listMap = (Map<String, List<List<String>>>) map.get("tableList");
if (listMap != null) {
Object[] arr = new Object[]{};
if (listMap.containsKey("table1")) {
List<List<String>> lists1 = listMap.get("table1");
if (lists1.size() > 0) {
arr = new Object[]{"table", "table1"};
} else {
arr = new Object[]{"table"};
}
}else {
arr = new Object[]{"table"};
arr = new Object[]{"tableInfo"};
}
// for (Object key : arr) {
List<List<String>> lists = listMap.get("table");
List<List<String>> listInfo = listMap.get("tableInfo");
List<List<String>> listBy = listMap.get("table1");
//判断
if (listBy!= null && listBy.size()>0) {
//遍历数据添加序号
for (int i = 0; i < listBy.size(); i++) {
List<String> list = listBy.get(i);
// List<String> list = listBy.get(0);
String data = list.get(0);
String on = i + 1 + " " + data;
// String on = 0 + 1 + " " + data;
list.set(0, on);}
int pageNo = 0;
if (form.getFieldPositions("table1") == null) {
pageNo = 0;
} else {
pageNo = form.getFieldPositions("table1").get(0).page;
}
PdfContentByte pcb = stamper.getOverContent(pageNo);
List<AcroFields.FieldPosition> listAf = form.getFieldPositions("table1");
Rectangle signRect = listAf.get(0).position;
//表格位置
int columnInfo = listBy.get(0).size();
int rowInfo = listBy.size();
PdfPTable tableInfo = new PdfPTable(columnInfo);
// float tatalWidth = signRect.getRight() - signRect.getLeft() - 1;
tableInfo.setTotalWidth(width);
tableInfo.setLockedWidth(true);
tableInfo.setKeepTogether(true);
tableInfo.setSplitLate(false);
tableInfo.setSplitRows(true);
Font FontProve = new Font(bf, 8, 0);
//表格数据填写
for (int k = 0; k < rowInfo; k++) {
List<String> listTo = listBy.get(k);
// List<String> listTo = listBy.get(i);
for (int j = 0; j < columnInfo; j++) {
Paragraph paragraph = new Paragraph(String.valueOf(listTo.get(j)), FontProve);
PdfPCell cell = new PdfPCell(paragraph);
cell.setBorderWidth(1);
cell.setMinimumHeight(1);
if (j == 0) {
cell.setVerticalAlignment(Element.ALIGN_LEFT);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
} else {
cell.setVerticalAlignment(Element.ALIGN_CENTER);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
}
cell.setLeading(0, (float) 1.4);
cell.disableBorderSide(15);//隐藏
tableInfo.addCell(cell);
}
}
tableInfo.writeSelectedRows(0, -1, signRect.getLeft(), signRect.getTop(), pcb);
// }
}
if (listInfo!= null && listInfo.size()>0) {
//遍历数据添加序号
for (int i = 0; i < listInfo.size(); i++) {
List<String> list = listInfo.get(i);
String data = list.get(0);
String on = i + 1 +" " + data ;
list.set(0,on);
}
int pageNo = 0;
if (form.getFieldPositions("tableInfo") == null) {
pageNo = 0;
} else {
pageNo = form.getFieldPositions("tableInfo").get(0).page;
}
PdfContentByte pcb = stamper.getOverContent(pageNo);
List<AcroFields.FieldPosition> listAf = form.getFieldPositions("tableInfo");
Rectangle signRect = listAf.get(0).position;
//表格位置
int columnInfo = listInfo.get(0).size();
int rowInfo = listInfo.size();
PdfPTable tableInfo = new PdfPTable(columnInfo);
float tatalWidth = signRect.getRight() - signRect.getLeft() - 1;
//
tableInfo.setTotalWidth(tatalWidth);
tableInfo.setLockedWidth(true);
tableInfo.setKeepTogether(true);
tableInfo.setSplitLate(false);
tableInfo.setSplitRows(true);
Font FontProve = new Font(bf, 8, 0);
//表格数据填写
for (int i = 0; i < rowInfo; i++) {
List<String> list = listInfo.get(i);
for (int j = 0; j < columnInfo; j++) {
Paragraph paragraph = new Paragraph(String.valueOf(list.get(j)), FontProve);
PdfPCell cell = new PdfPCell(paragraph);
cell.setBorderWidth(1);
cell.setMinimumHeight(1);
if (j == 0) {
cell.setVerticalAlignment(Element.ALIGN_LEFT);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
} else {
cell.setVerticalAlignment(Element.ALIGN_CENTER);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
}
cell.setLeading(0, (float) 1.4);
cell.disableBorderSide(15);//隐藏
tableInfo.addCell(cell);
}
}
System.out.println(signRect.getLeft());
System.out.println(signRect.getTop());
System.out.println(pcb);
tableInfo.writeSelectedRows(0, -1, signRect.getLeft(), signRect.getTop(), pcb);
}
if (lists!= null && lists.size()>0) {
//遍历数据添加序号
for (int i = 0; i < lists.size(); i++) {
List<String> list = lists.get(i);
String data = list.get(0);
String on = i + 1 +" "+ data ;
list.set(0,on);
}
int pageNo = 0;
if (form.getFieldPositions("table") == null) {
pageNo = 0;
} else {
pageNo = form.getFieldPositions("table").get(0).page;
}
PdfContentByte pcb = stamper.getOverContent(pageNo);
List<AcroFields.FieldPosition> listAf = form.getFieldPositions("table");
Rectangle signRect = listAf.get(0).position;
//表格位置
int column = lists.get(0).size();
int row = lists.size();
PdfPTable table = new PdfPTable(column);
// float tatalWidth = signRect.getRight() - signRect.getLeft() - 1;
// table.setTotalWidth(width);
table.setLockedWidth(true);
table.setKeepTogether(true);
table.setSplitLate(false);
table.setSplitRows(true);
Font FontProve = new Font(bf, 8, 0);
//表格数据填写
for (int i = 0; i < row; i++) {
List<String> list = lists.get(i);
for (int j = 0; j < column; j++) {
Paragraph paragraph = new Paragraph(String.valueOf(list.get(j)), FontProve);
PdfPCell cell = new PdfPCell(paragraph);
cell.setBorderWidth(1);
cell.setMinimumHeight(1);
if (j == 0) {
cell.setVerticalAlignment(Element.ALIGN_LEFT);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
} else {
cell.setVerticalAlignment(Element.ALIGN_CENTER);
cell.setHorizontalAlignment(Element.ALIGN_CENTER);
}
cell.setLeading(0, (float) 1.4);
cell.disableBorderSide(15);//隐藏
table.addCell(cell);
}
}
table.writeSelectedRows(1, -1, signRect.getLeft(), signRect.getTop(), pcb);
}
}
// 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑
stamper.setFormFlattening(true);
stamper.close();
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, out);
doc.open();
// File file = new File("ruoyi-admin/src/main/resources/static/pdf/111.pdf");
// File file = new File("D:\\feishu\\yihe\\111.pdf");
//本地路径
File file = new File("E:\\item\\yihe\\ruoyi-admin\\src\\main\\resources\\static\\pdf\\111.pdf");
//线上路径
// File file = new File("D:\\feishu\\yihe\\111.pdf");
PdfCopy copy1 = new PdfCopy(doc, new FileOutputStream(file));
doc.open();
int pageNum = reader.getNumberOfPages();
for (int i = 1; i <= pageNum; i++) {
PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), i);
copy.addPage(importPage);
copy1.addPage(importPage);
}
// String url = AliyunOSSUtil.upload(getMultipartFile(file));
// System.out.println("url = " + url);
doc.close();
return "url";
}