目錄
1、引入jar包
2、pdf處理工具類
3、poi模板導(dǎo)出工具類
4、測試類
5、模板
6、最終效果?
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;
//數(shù)值越大每頁豎向水印越少
private static int heightDensity = 15;
//數(shù)值越大每頁橫向水印越少
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 轉(zhuǎn)換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)) {
// 暫不實(shí)現(xiàn),需要引入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); // 新建一個(gè)空白pdf文檔
FileOutputStream os = new FileOutputStream(file);
Document doc = new Document(inputFile); // inputFile是將要被轉(zhuǎn)化的word文檔
//全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF, EPUB, XPS, SWF 相互轉(zhuǎn)換
doc.save(os, com.aspose.words.SaveFormat.PDF);
os.close();
System.out.println(">>>>>>>>>> word文件轉(zhuǎn)換pdf成功!");
long now = System.currentTimeMillis();
System.out.println("共耗時(shí):" + ((now - old) / 1000.0) + "秒"); // 轉(zhuǎn)化用時(shí)
} catch (Exception e) {
e.printStackTrace();
}
}
private static boolean getLicense2() {
boolean result = false;
try {
InputStream is = PdfUtil.class.getClassLoader()
.getResourceAsStream("license.xml"); // license.xml應(yīng)放在..\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()) { // 驗(yàn)證License 若不驗(yàn)證則轉(zhuǎn)化出的pdf文檔會有水印產(chǎn)生
return;
}
try {
Workbook wb = new Workbook(excelPath);// 原始excel路徑
File pdfFile = new File(pdfPath);// 輸出路徑
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
//把excel所有內(nèi)容放在一張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文件轉(zhuǎn)換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();
//這里是透明度設(shè)置
gs.setFillOpacity(opacity);
//這里是條紋不透明度
gs.setStrokeOpacity(0.2f);
int total = reader.getNumberOfPages() + 1;
System.out.println("Pdf頁數(shù):" + reader.getNumberOfPages());
JLabel label = new JLabel();
FontMetrics metrics;
int textH = 0;
int textW = 0;
label.setText(waterMarkName);
metrics = label.getFontMetrics(label.getFont());
//字符串的高, 只和字體有關(guān)
textH = metrics.getHeight();
//字符串的寬
textW = metrics.stringWidth(label.getText());
PdfContentByte under;
//循環(huán)PDF,每頁添加水印
for (int i = 1; i < total; i++) {
pageRect = reader.getPageSizeWithRotation(i);
//在內(nè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("添加水印失敗!錯(cuò)誤信息為: " + e);
return false;
} catch (DocumentException e) {
System.out.println("添加水印失??!錯(cuò)誤信息為: " + e);
return false;
} finally {
//關(guān)閉流
if (stamper != null) {
try {
stamper.close();
} catch (DocumentException e) {
System.out.println("文件流關(guān)閉失敗");
} catch (IOException e) {
System.out.println("文件流關(guān)閉失敗");
}
}
if (reader != null) {
reader.close();
}
}
}
}
?3、poi模板導(dǎo)出工具類
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) {
//判斷此段落是否需要進(jìn)行替換
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) {// 復(fù)選框填充值
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);
}
}
}
}
}
/**
* 復(fù)制表頭 插入行數(shù)據(jù),這里樣式和表頭一樣
* @param document docx解析對象
* @param tableList 需要插入數(shù)據(jù)集合
* @param tableIndex 表格索引,在word表格對象集合中是第幾個(gè)表格,從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;
}
//遍歷要添加的數(shù)據(jù)的list
for (int i = 0; i < tableList.size(); i++) {
//插入一行
XWPFTableRow targetRow = tables.get(tableindex).insertNewTableRow(headerIndex + i);
//復(fù)制行屬性
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);
//插入一個(gè)單元格
XWPFTableCell targetCell = targetRow.addNewTableCell();
//復(fù)制列屬性
targetCell.getCTTc().setTcPr(sourceCell.getCTTc().getTcPr());
//targetCell.setText(entry.getValue());
/** XWPFTableCell 無法直接設(shè)置字體樣式,故換一種方式 **/
//獲取 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 設(shè)置格式
XWPFRun run = par.createRun();
String textValue = entry.getValue();
// 復(fù)選框填充值
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++) {
//只處理行數(shù)大于等于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) {// 復(fù)選框填充值
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 模板需要替換的區(qū)域
* @param textMap 傳入信息集合
* @return 模板需要替換區(qū)域信息集合對應(yīng)值
*/
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();
}
}
//模板未匹配到區(qū)域替換為空
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[]){
// 開始時(shí)間
long stime = System.currentTimeMillis();
// 模擬點(diǎn)數(shù)據(jù)
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經(jīng)濟(jì)適用房" + "@@@"
+ "\u2611限價(jià)房" + "@@@" + "\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經(jīng)濟(jì)適用房" + "@@@"
+ "\u2611限價(jià)房" + "@@@" + "\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);
// 結(jié)束時(shí)間
long etime = System.currentTimeMillis();
// 計(jì)算執(zhí)行時(shí)間
System.out.printf("執(zhí)行時(shí)長:%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", "導(dǎo)入模板");
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 轉(zhuǎn) pdf
PdfUtil.transToPdf(f1.getPath(), f2.getPath(), suffix);
// itextpdf給pdf加水印
PdfUtil.addWaterMark(f2.getPath(), f3.getPath(), "測試水印", true);
}
}
5、模板
文章來源:http://www.zghlxwxcb.cn/news/detail-740802.html
6、最終效果?
文章來源地址http://www.zghlxwxcb.cn/news/detail-740802.html
到了這里,關(guān)于(Java)word轉(zhuǎn)pdf(aspose),pdf加水印(itextpdf),并支持POI模板(包括checkbox)導(dǎo)出的文章就介紹完了。如果您還想了解更多內(nèi)容,請?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!