目录
1、引入jar包
2、pdf处理工具类
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.aspose.words.Document; //引入aspose-words-21.5.0-jdk17包
import com.aspose.words.*;
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
import javax.swing.JLabel;
import java.awt.FontMetrics;
import java.io.*;
import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.Arrays;
public class PdfUtil {
//水印字体透明度
private static float opacity = 0.1f;
//水印字体大小
private static int fontsize = 20;
//水印倾斜角度(0-360)
private static int angle = 30;
//数值越大每页竖向水印越少
private static int heightDensity = 15;
//数值越大每页横向水印越少
private static int widthDensity = 2;
private static final String[] WORD = {"doc", "docx", "wps", "wpt", "txt"};
private static final String[] EXCEL = {"xls", "xlsx", "et", "xlsm"};
private static final String[] PPT = {"ppt", "pptx"};
/**
* transToPdf 转换pdf
* @param filePath 输入文件路径
* @param pdfPath 输出pdf文件路径
* @param suffix 输入文件后缀
*/
public static void transToPdf(String filePath, String pdfPath, String suffix) {
if (Arrays.asList(WORD).contains(suffix)) {
word2PDF(filePath, pdfPath);
} else if (Arrays.asList(EXCEL).contains(suffix)) {
excel2PDF(filePath, pdfPath);
} else if (Arrays.asList(PPT).contains(suffix)) {
// 暂不实现,需要引入aspose.slides包
}
}
private static void word2PDF(String inputFile, String pdfFile) {
try {
Class<?> aClass = Class.forName("com.aspose.words.zzZDQ");
Field zzYAC = aClass.getDeclaredField("zzYAC");
zzYAC.setAccessible(true);
Field modifiersField = Field.class.getDeclaredField("modifiers");
modifiersField.setAccessible(true);
modifiersField.setInt(zzYAC, zzYAC.getModifiers() & ~Modifier.FINAL);
zzYAC.set(null,new byte[]{76, 73, 67, 69, 78, 83, 69, 68});
long old = System.currentTimeMillis();
File file = new File(pdfFile); // 新建一个空白pdf文档
FileOutputStream os = new FileOutputStream(file);
Document doc = new Document(inputFile); // inputFile是将要被转化的word文档
//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互转换
doc.save(os, com.aspose.words.SaveFormat.PDF);
os.close();
System.out.println(">>>>>>>>>> word文件转换pdf成功!");
long now = System.currentTimeMillis();
System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
} catch (Exception e) {
e.printStackTrace();
}
}
private static boolean getLicense2() {
boolean result = false;
try {
InputStream is = PdfUtil.class.getClassLoader()
.getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
com.aspose.cells.License aposeLic = new com.aspose.cells.License();
aposeLic.setLicense(is);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
private static void excel2PDF(String excelPath, String pdfPath) {
if (!getLicense2()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
return;
}
try {
Workbook wb = new Workbook(excelPath);// 原始excel路径
File pdfFile = new File(pdfPath);// 输出路径
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
//把excel所有内容放在一张PDF 页面上;
pdfSaveOptions.setOnePagePerSheet(false);
//把excel所有表头放在一张pdf上
pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
FileOutputStream fileOS = new FileOutputStream(pdfFile);
wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
fileOS.close();
System.out.println(">>>>>>>>>> excel文件转换pdf成功!");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* pdf添加水印
*
* @param inputFile 需要添加水印的文件
* @param outputFile 添加完水印的文件存放路径
* @param waterMarkName 需要添加的水印文字
* @param cover 是否覆盖
* @return
*/
public static boolean addWaterMark(String inputFile, String outputFile, String waterMarkName, boolean cover) {
if (!cover) {
File file = new File(outputFile);
if (file.exists()) {
return true;
}
}
File file = new File(inputFile);
if (!file.exists()) {
return false;
}
PdfReader reader = null;
PdfStamper stamper = null;
try {
reader = new PdfReader(inputFile);
stamper = new PdfStamper(reader, new FileOutputStream(outputFile));
BaseFont base = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED);
Rectangle pageRect = null;
PdfGState gs = new PdfGState();
//这里是透明度设置
gs.setFillOpacity(opacity);
//这里是条纹不透明度
gs.setStrokeOpacity(0.2f);
int total = reader.getNumberOfPages() + 1;
System.out.println("Pdf页数:" + reader.getNumberOfPages());
JLabel label = new JLabel();
FontMetrics metrics;
int textH = 0;
int textW = 0;
label.setText(waterMarkName);
metrics = label.getFontMetrics(label.getFont());
//字符串的高, 只和字体有关
textH = metrics.getHeight();
//字符串的宽
textW = metrics.stringWidth(label.getText());
PdfContentByte under;
//循环PDF,每页添加水印
for (int i = 1; i < total; i++) {
pageRect = reader.getPageSizeWithRotation(i);
//在内容上方添加水印
under = stamper.getOverContent(i);
under.saveState();
under.setGState(gs);
under.beginText();
//这里是水印字体大小
under.setFontAndSize(base, fontsize);
for (int height = textH; height < pageRect.getHeight() * 2; height = height + textH * heightDensity) {
for (int width = textW; width < pageRect.getWidth() * 1.5 + textW; width = width + textW * widthDensity) {
// rotation:倾斜角度
under.showTextAligned(Element.ALIGN_LEFT, waterMarkName, width - textW, height - textH, angle);
}
}
//添加水印文字
under.endText();
}
System.out.println("添加水印成功!");
return true;
} catch (IOException e) {
System.out.println("添加水印失败!错误信息为: " + e);
return false;
} catch (DocumentException e) {
System.out.println("添加水印失败!错误信息为: " + e);
return false;
} finally {
//关闭流
if (stamper != null) {
try {
stamper.close();
} catch (DocumentException e) {
System.out.println("文件流关闭失败");
} catch (IOException e) {
System.out.println("文件流关闭失败");
}
}
if (reader != null) {
reader.close();
}
}
}
}
3、poi模板导出工具类
import java.util.*;
import org.apache.poi.xwpf.usermodel.*;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTP;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTc;
public class ExportWordUtil {
private ExportWordUtil() {
}
/**
* 替换文档中段落文本
*
* @param document docx解析对象
* @param textMap 需要替换的信息集合
*/
public static void changeParagraphText(XWPFDocument document, Map<String, String> textMap) {
//获取段落集合
List<XWPFParagraph> paragraphs = document.getParagraphs();
for (XWPFParagraph paragraph : paragraphs) {
//判断此段落是否需要进行替换
String text = paragraph.getText();
if (checkText(text)) {
List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun run : runs) {
//替换模板原来位置
String textValue = changeValue(run.toString(), textMap);
if (run.toString().toLowerCase().indexOf("checkbox_") != -1) {// 复选框填充值
run.setFontFamily("SimSun");
String[] tArr = textValue.split("@@@");
for (int i = 0; i < tArr.length; i++) {
if (i == 0) {
run.setText(tArr[i], 0);
} else {
run.setText(tArr[i]);
}
if (i != tArr.length-1) {
run.addBreak();//换行
}
}
} else {
run.setText(textValue, 0);
}
}
}
}
}
/**
* 复制表头 插入行数据,这里样式和表头一样
* @param document docx解析对象
* @param tableList 需要插入数据集合
* @param tableIndex 表格索引,在word表格对象集合中是第几个表格,从0开始
* @param headerIndex 表头的行索引,从0开始
*/
public static void copyHeaderInsertText(XWPFDocument document, List<Map<String,String>> tableList, String[] fields, int tableindex, int headerIndex){
if(null == tableList || null == fields){
return;
}
//获取表格对象集合
List<XWPFTable> tables = document.getTables();
XWPFTableRow copyRow = tables.get(tableindex).getRow(headerIndex);
List<XWPFTableCell> cellList = copyRow.getTableCells();
if (null == cellList) {
return;
}
//遍历要添加的数据的list
for (int i = 0; i < tableList.size(); i++) {
//插入一行
XWPFTableRow targetRow = tables.get(tableindex).insertNewTableRow(headerIndex + i);
//复制行属性
targetRow.getCtRow().setTrPr(copyRow.getCtRow().getTrPr());
Map<String,String> map = tableList.get(i);
// 字段匹配后,插入单元格并赋值
for (String field : fields) {
int idx = 0;
for(Map.Entry<String,String> entry: map.entrySet()){
if(!field.equals(entry.getKey())) continue;
XWPFTableCell sourceCell = cellList.get(idx);
//插入一个单元格
XWPFTableCell targetCell = targetRow.addNewTableCell();
//复制列属性
targetCell.getCTTc().setTcPr(sourceCell.getCTTc().getTcPr());
//targetCell.setText(entry.getValue());
/** XWPFTableCell 无法直接设置字体样式,故换一种方式 **/
//获取 XWPFTableCell 的CTTc
CTTc ctTc = targetCell.getCTTc();
//获取 CTP
CTP ctP = (ctTc.sizeOfPArray() == 0) ? ctTc.addNewP() : ctTc.getPArray(0);
//getParagraph(ctP) 获取 XWPFParagraph
XWPFParagraph par = targetCell.getParagraph(ctP);
//XWPFRun 设置格式
XWPFRun run = par.createRun();
String textValue = entry.getValue();
// 复选框填充值
if (field.toLowerCase().indexOf("checkbox_") != -1) {
run.setFontFamily("SimSun");
String[] tArr = textValue.split("@@@");
for (int j = 0; j < tArr.length; j++) {
if (j == 0) {
run.setText(tArr[j], 0);
} else {
run.setText(tArr[j]);
}
if (j != tArr.length-1) {
run.addBreak();//换行
}
}
} else {
run.setText(textValue, 0);
}
idx ++;
};
}
}
if (tableList.size() > 0) {
List<XWPFTableRow> rows = tables.get(tableindex).getRows();
int rowLength = rows.size();
deleteTable(tables.get(tableindex), tableList.size() + headerIndex, rowLength);
}
}
/**
* 删除表格行
* @param table 表格对象
* @param fromIndex 从第几行,从0开始
* @param toIndex 到第几行,从0开始
*/
public static void deleteTable(XWPFTable table, int fromIndex, int toIndex){
for (int i = fromIndex; i < toIndex; i++) {
table.removeRow(fromIndex);
}
}
/**
* 替换表格对象方法
*
* @param document docx解析对象
* @param textMap 需要替换的信息集合
*/
public static void changeTableText(XWPFDocument document, Map<String, String> textMap) {
//获取表格对象集合
List<XWPFTable> tables = document.getTables();
for (int i = 0; i < tables.size(); i++) {
//只处理行数大于等于2的表格
XWPFTable table = tables.get(i);
if (table.getRows().size() > 1) {
//判断表格是需要替换还是需要插入,判断逻辑有$为替换
if (checkText(table.getText())) {
List<XWPFTableRow> rows = table.getRows();
//遍历表格,并替换模板
eachTable(rows, textMap);
}
}
}
}
/**
* 遍历表格,并替换模板
*
* @param rows 表格行对象
* @param textMap 需要替换的信息集合
*/
public static void eachTable(List<XWPFTableRow> rows, Map<String, String> textMap) {
for (XWPFTableRow row : rows) {
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
//判断单元格是否需要替换
if (checkText(cell.getText())) {
List<XWPFParagraph> paragraphs = cell.getParagraphs();
for (XWPFParagraph paragraph : paragraphs) {
List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun run : runs) {
String textValue = changeValue(run.toString(), textMap);
if (run.toString().toLowerCase().indexOf("checkbox_") != -1) {// 复选框填充值
run.setFontFamily("SimSun");
String[] tArr = textValue.split("@@@");
for (int i = 0; i < tArr.length; i++) {
if (i == 0) {
run.setText(tArr[i], 0);
} else {
run.setText(tArr[i]);
}
if (i != tArr.length-1) {
run.addBreak();//换行
}
}
} else {
run.setText(textValue, 0);
}
}
}
}
}
}
}
/**
* 匹配传入信息集合与模板
*
* @param value 模板需要替换的区域
* @param textMap 传入信息集合
* @return 模板需要替换区域信息集合对应值
*/
public static String changeValue(String value, Map<String, String> textMap) {
Set<Map.Entry<String, String>> textSets = textMap.entrySet();
for (Map.Entry<String, String> textSet : textSets) {
//匹配模板与替换值 格式${key}
String key = "${" + textSet.getKey() + "}";
if (value.indexOf(key) != -1) {
value = textSet.getValue();
}
}
//模板未匹配到区域替换为空
if (checkText(value)) {
value = "";
}
return value;
}
/**
* 判断文本中是否包含$
*
* @param text 文本
* @return 包含返回true, 不包含返回false
*/
public static boolean checkText(String text) {
boolean check = false;
if (text.indexOf("$") != -1) {
check = true;
}
return check;
}
}
4、测试类
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import java.io.*;
import java.util.*;
/**
* @ClassName: Mytest
* @Description: 测试类
* @Suthor: mxch
* @Create: 2023-05-13
**/
public class Mytest {
public static void main(String args[]){
// 开始时间
long stime = System.currentTimeMillis();
// 模拟点数据
Map<String, String> paragraphMap = new HashMap<>();
Map<String, String> tableMap = new HashMap<>();
paragraphMap.put("name", "赵云");
paragraphMap.put("date", "2020-03-25");
paragraphMap.put("checkbox_sf", "\u25A1是" + " " + "\u2611否");
tableMap.put("name", "赵云");
tableMap.put("sex", "男");
tableMap.put("birthday", "2020-01-01");
tableMap.put("checkbox_sf", "\u25A1是s" + " " + "\u2611否d" + "@@@" + "\u25A1是" + " " + "\u2611否");
List<Map<String,Object>> tableDatalist = new ArrayList<>();
/*************清单1****************/
List<Map<String,String>> familyList = new ArrayList<>();
Map m = new HashMap();
m.put("name","露娜");
m.put("sex","女");
m.put("position","野友");
m.put("no","6660");
familyList.add(m);
m = new HashMap();
m.put("name","鲁班");
m.put("sex","男");
m.put("position","射友");
m.put("no","2220");
familyList.add(m);
m = new HashMap();
m.put("name","程咬金");
m.put("sex","男");
m.put("position","肉友");
m.put("no","9990");
familyList.add(m);
Map tableData = new HashMap();
tableData.put("list", familyList);
tableData.put("fields", new String[]{"name","sex","position","no"});
tableData.put("tableIndex", 1);
tableData.put("headerIndex", 1);
tableDatalist.add(tableData);
/*************清单2****************/
familyList = new ArrayList<>();
m = new HashMap();
m.put("name","太乙真人");
m.put("sex","男");
m.put("position","辅友");
m.put("no","1110");
m.put("checkbox_fcxz", "\u25A1商品房" + "@@@" + "\u2611福利房" + "@@@" + "\u25A1经济适用房" + "@@@"
+ "\u2611限价房" + "@@@" + "\u2611自建房" + "@@@" + "\u25A1车库、车位、储藏间" + "@@@" + "\u25A1其他");
familyList.add(m);
m = new HashMap();
m.put("name","貂蝉");
m.put("sex","女");
m.put("position","法友");
m.put("no","8880");
m.put("checkbox_fcxz", "\u25A1商品房" + "@@@" + "\u2611福利房" + "@@@" + "\u2611经济适用房" + "@@@"
+ "\u2611限价房" + "@@@" + "\u2611自建房" + "@@@" + "\u2611车库、车位、储藏间" + "@@@" + "\u25A1其他");
familyList.add(m);
tableData = new HashMap();
tableData.put("list", familyList);
tableData.put("fields", new String[]{"name","sex","position","checkbox_fcxz"});
tableData.put("tableIndex", 2);
tableData.put("headerIndex", 1);
tableDatalist.add(tableData);
exportWord(paragraphMap,tableMap,tableDatalist);
// 结束时间
long etime = System.currentTimeMillis();
// 计算执行时间
System.out.printf("执行时长:%d 毫秒.", (etime - stime));
}
@SuppressWarnings("unchecked")
private static void exportWord(Map<String, String> paragraphMap,Map<String, String> tableMap,List<Map<String,Object>> tableDatalist){
String classpath = Mytest.class.getClass().getResource("/").getPath();
String templatePath = classpath.replace("WEB-INF/classes", "导入模板");
String t_filepath = classpath.replace("WEB-INF/classes", "import");
String filename = "person";
File f = new File(templatePath + filename + ".docx");
File f1 = new File(t_filepath + filename + ".docx");
File f2 = new File(t_filepath + filename + ".pdf");
File f3 = new File(t_filepath + filename + "_水印.pdf");
XWPFDocument document = null;
try {
//解析docx模板并获取document对象
document = new XWPFDocument(new FileInputStream(new File(f.getPath())));
ExportWordUtil.changeParagraphText(document, paragraphMap);
ExportWordUtil.changeTableText(document, tableMap);
for (Map<String,Object> map : tableDatalist) {
ExportWordUtil.copyHeaderInsertText(document, (List<Map<String,String>>) map.get("list"), (String[]) map.get("fields"),
(Integer) map.get("tableIndex"), (Integer) map.get("headerIndex"));
}
FileOutputStream out = new FileOutputStream(new File(f1.getPath()));
document.write(out);
out.close();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (document != null) {
try {
document.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
String suffix = f1.getPath().substring(f1.getPath().lastIndexOf(".") + 1); // 后缀
// aspose 转 pdf
PdfUtil.transToPdf(f1.getPath(), f2.getPath(), suffix);
// itextpdf给pdf加水印
PdfUtil.addWaterMark(f2.getPath(), f3.getPath(), "测试水印", true);
}
}