目录
1.引包
项目要使用iText,必须引入jar包。才能使用,maven依赖如下:
<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.5.11</version> </dependency>
二维码生成
<dependency> <groupId>com.google.zxing</groupId> <artifactId>core</artifactId> <version>3.3.0</version> </dependency>
2.工具类
package com.zz.common.utils;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import lombok.extern.slf4j.Slf4j;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;
import java.util.Map;
/**
* pdf工具类
*
* @author zhooulianjie
* @date 2021/2/3
*/
@Slf4j
public class PdfUtils<main> {
/**
* pdf添加水印
*
* @param outputFile 添加完水印的文件输出地址
* @param inputFile 原PDF文件地址
* @param word 水印内容
* @param model 水印添加位置1中间,2两边
*/
public static void setPdfWatermark(String outputFile, String inputFile, String word, int model) {
PdfReader reader;
try {
BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(new File(outputFile)));
FileInputStream input = new FileInputStream(inputFile);
reader = new PdfReader(input);
PdfStamper stamper = new PdfStamper(reader, bos);
PdfContentByte content;
// 创建字体
BaseFont base = BaseFont.createFont("C:/WINDOWS/Fonts/simhei.ttf", BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
PdfGState gs = new PdfGState();
// 获取PDF页数
int total = reader.getNumberOfPages();
// 遍历每一页
for (int i = 0; i < total; i++) {
// 页宽度
float width = reader.getPageSize(i + 1).getWidth();
// 页高度
float height = reader.getPageSize(i + 1).getHeight();
// 内容
content = stamper.getOverContent(i + 1);
//开始写入文本
content.beginText();
//水印透明度
gs.setFillOpacity(0.9f);
content.setGState(gs);
content.setColorFill(BaseColor.LIGHT_GRAY);
//设置字体的输出位置
content.setTextMatrix(70, 200);
if (model == 1) {
// 平行居中的3条水印
// 字体大小
content.setFontAndSize(base, 30);
//showTextAligned 方法的参数分别是(文字对齐方式,位置内容,输出
// .水印X轴位置,Y轴位置,旋转角度)
content.showTextAligned(Element.ALIGN_CENTER, word, width / 2, 800, 30);
content.showTextAligned(Element.ALIGN_CENTER, word, width / 2, 600, 30);
content.showTextAligned(Element.ALIGN_CENTER, word, width / 2, 400, 30);
content.showTextAligned(Element.ALIGN_CENTER, word, width / 2, 200, 30);
content.showTextAligned(Element.ALIGN_CENTER, word, width / 2, 0, 30);
} else {
// 左右两边个从上到下4条水印
// 水印旋转度数
float rotation = 30;
content.setFontAndSize(base, 20);
content.showTextAligned(Element.ALIGN_LEFT, word, 20, height - 50, rotation);
content.showTextAligned(Element.ALIGN_LEFT, word, 20, height / 4 * 3 - 50, rotation);
content.showTextAligned(Element.ALIGN_LEFT, word, 20, height / 2 - 50, rotation);
content.showTextAligned(Element.ALIGN_LEFT, word, 20, height / 4 - 50, rotation);
content.setFontAndSize(base, 22);
content.showTextAligned(Element.ALIGN_RIGHT, word, width - 20, height - 50, rotation);
content.showTextAligned(Element.ALIGN_RIGHT, word, width - 20, height / 4 * 3 - 50, rotation);
content.showTextAligned(Element.ALIGN_RIGHT, word, width - 20, height / 2 - 50, rotation);
content.showTextAligned(Element.ALIGN_RIGHT, word, width - 20, height / 4 - 50, rotation);
}
//结束写入文本
content.endText();
//要打图片水印的话
//Image image = Image.getInstance("c:/1.jpg");
//content.addImage(image);
}
stamper.close();
} catch (IOException | DocumentException e) {
log.error("pdf添加水印失败,原因:" + e.getMessage());
}
}
// 利用模板生成pdf
public static void pdfout(String templatePath, String fileName, Map<String, List<Map<String, Object>>> o, HttpServletResponse response) {
// 生成的新文件路径
String property = System.getProperty("user.dir");
String newPDFPath = property + "/files/" + fileName + ".pdf";
FileOutputStream out;
try {
out = new FileOutputStream(newPDFPath);// 输出流
Document doc = new Document();
PdfCopy copy = new PdfCopy(doc, out);
doc.open();
List<Map<String, Object>> mapList = o.get("datemap");
List<Map<String, Object>> imgList = o.get("imgmap");
for (int i = 0; i < mapList.size(); i++) {
PdfReader reader = new PdfReader(templatePath);// 读取pdf模板
ByteArrayOutputStream bos;
PdfStamper stamper;
bos = new ByteArrayOutputStream();
stamper = new PdfStamper(reader, bos);
AcroFields form = stamper.getAcroFields();
//文字类的内容处理
for (String key : mapList.get(i).keySet()) {
String value = String.valueOf(mapList.get(i).get(key));
form.setField(key, value);
}
//图片类的内容处理
for(String key : imgList.get(i).keySet()) {
String value = String.valueOf(imgList.get(i).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();
//根据路径读取图片
File file = new File(imgpath);
if (file.exists()) {
Image image = Image.getInstance(imgpath);
//获取图片页面
PdfContentByte under = stamper.getOverContent(pageNo);
//图片大小自适应
image.scaleToFit(signRect.getWidth(), signRect.getHeight());
//添加图片
image.setAbsolutePosition(x, y);
under.addImage(image);
}
}
stamper.setFormFlattening(true);// 如果为false,生成的PDF文件可以编辑,如果为true,生成的PDF文件不可以编辑
stamper.close();
PdfImportedPage importPage = copy.getImportedPage(new PdfReader(bos.toByteArray()), 1);
copy.addPage(importPage);
}
doc.close();
FileUtils.downLoad(newPDFPath, fileName + ".pdf", response);
FileUtils.deleteFile(newPDFPath);
} catch (IOException e) {
System.out.println(e);
} catch (DocumentException e) {
System.out.println(e);
}
}
}
3.数据构建
@Override
public void printpdf(HttpServletResponse response) {
QueryWrapper<T> query = new QueryWrapper<>();
List<Map<String, Object>> ryxq = this.list(query);
List<Map<String, Object>> zpMap = new ArrayList<Map<String, Object>>();
Map<String, List<Map<String, Object>>> map = new HashMap<String, List<Map<String, Object>>>();
ryxq.forEach(m -> {
Map<String, Object> retMap = new HashMap<>();
if (Utils.notEmpty(m.get("lczp"))) {
retMap.put("lczpPath", "照片地址");
}
String destPath = "二维码存储地址";
String ewmcs = "二维码信息";
try {
EwmUtil.encode(ewmcs, destPath);
retMap.put("ewmPath", destPath);
} catch (Exception e) {
e.printStackTrace();
}
zpMap.add(retMap);
});
map.put("datemap", ryxq);
map.put("imgmap", zpMap);
PdfUtils.pdfout(System.getProperty("user.dir") + bmzsmb_url, "zhengshu", map, response);
}
4.pdf模板
5.输出