IText创建加盖公章的pdf文件并生成压缩文件
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.Map;
import java.util.Objects;
import java.util.zip.ZipEntry;
import java.util.zip.ZipOutputStream;
import com.itextpdf.text.Image;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.AcroFields;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfContentByte;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfWriter;
public final class CommonFileUtil {
private final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CommonFileUtil.class);
/**
* 根据模板生成文件
* @param paramMap
* @param deskFile
* @param template
* @param gongZhang
* @throws Exception
*/
public static void create(Map<String, Object> paramMap, File deskFile, final byte[] template, final byte[] gongZhang) throws Exception {
PdfReader reader = null;
PdfStamper stamp = null;
try {
reader = new PdfReader(template);
stamp = new PdfStamper(reader, new FileOutputStream(deskFile));
stamp.setEncryption(null, "lsy2024".getBytes(), PdfWriter.ALLOW_PRINTING, true);
//取出报表模板中的所有字段
AcroFields form = stamp.getAcroFields();
//设置宋体
BaseFont song = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
//设置参数
for (Map.Entry<String, Object> entry : paramMap.entrySet()) {
String key = entry.getKey();
form.setFieldProperty(key, "textfont", song, null);
form.setField(key, entry.getValue().toString());
}
//插入公章
CommonFileUtil.insertImage(form, stamp, "gongzhang", gongZhang);
//保存修改
stamp.setFormFlattening(true);
} catch (Throwable e) {
logger.error("deskFile:{};文件生成失败!", deskFile, e);
throw e;
} finally {
if (Objects.nonNull(stamp)) {
stamp.close();
}
if (Objects.nonNull(reader)) {
reader.close();
}
}
}
/**
* pdf模板插入图片
* @param form
* @param stamper
* @param filedName
* @param gongZhang
* @throws Exception
*/
public static void insertImage(AcroFields form, PdfStamper stamper, String filedName, final byte[] gongZhang) throws Exception {
final Rectangle signRect = form.getFieldPositions(filedName).get(0).position;
float x = signRect.getLeft();
float y = signRect.getBottom();
Image image = Image.getInstance(gongZhang);
// 获取操作的页面
PdfContentByte under = stamper.getOverContent(form.getFieldPositions(filedName).get(0).page);
// 根据域的大小缩放图片
image.scaleToFit(signRect.getWidth(), signRect.getHeight());
// 添加图片
image.setAbsolutePosition(x, y);
under.addImage(image);
}
/**
* 文件压缩
* @param sourcePath
* @param zipFilePath
* @throws Exception
*/
public static void encryptNoPassword(String sourcePath, String zipFilePath) throws Exception {
final long start = System.currentTimeMillis();
byte[] buf = new byte[1024];
File zipFile = new File(zipFilePath);
//zip文件不存在,则创建文件,用于压缩
ZipOutputStream zos = null;
try {
if (!zipFile.exists()) {
zipFile.createNewFile();
}
zos = new ZipOutputStream(new FileOutputStream(zipFile));
File file = new File(sourcePath);
for (File sourceFile : file.listFiles()) {
if (sourceFile == null || !sourceFile.exists()) {
continue;
}
try (FileInputStream fis = new FileInputStream(sourceFile)) {
//直接放到压缩包的根目录
zos.putNextEntry(new ZipEntry(sourceFile.getName()));
int len;
while ((len = fis.read(buf)) > 0) {
zos.write(buf, 0, len);
}
zos.closeEntry();
}
}
} catch (Throwable e) {
logger.error("sourcePath:{};zipFilePath:{};压缩文件失败!", sourcePath, zipFilePath, e);
throw e;
} finally {
if (zos != null) {
zos.close();
}
}
logger.info("sourcePath:{};zipFilePath:{};压缩文件结束!{}", sourcePath, zipFilePath, System.currentTimeMillis() - start);
}
/**
* 清理文件
* @param path
*/
public static void clean(String path) {
File rootPath = new File(path);
if (rootPath.exists()) {
if (rootPath.isDirectory()) {
for (File file : rootPath.listFiles()) {
clean(file.getPath());
}
}
if (rootPath.isFile() || rootPath.listFiles().length == 0) {
rootPath.delete();
}
}
}
}