主要的學習和踩坑
word模板1類型只有文字的只要用這種方式實現非常好,沒有圖片的word模板;特別注意的是支持.doc的模板
直接上代碼
1 word模板轉換工具類
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Map;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
/**
*
* 此處填寫類簡介
* <p>
* word生成
* </p>
* @author admin
* @since jdk1.6
* 2019年11月14日
*
*/
public class DocUtils {
/**
*
* @param tmpFile 模板文件路徑
* @param contentMap 需要替換的文字
* @param exportFile 輸出的文件路徑
* @throws FileNotFoundException
*/
public static void getBuild(String tmpFile, Map<String, Object> contentMap, String exportFile) throws FileNotFoundException{
//三種實現 InputStream 流方式
File f = new File(tmpFile);
InputStream in = new FileInputStream(f);
// 2 InputStream inputStream = DocUtil.class.getClassLoader().getResourceAsStream("static/book.doc");
// 3 InputStream inputStream1 = Thread.currentThread().getContextClassLoader().getResourceAsStream("content/book.docx");
HWPFDocument document = null;
try {
document = new HWPFDocument(in);
} catch (IOException e) {
e.printStackTrace();
}
// 讀取文本內容
Range bodyRange = document.getRange();
// 替換內容
for (Map.Entry<String, Object> entry : contentMap.entrySet()) {
bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue().toString());
}
//導出到文件
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
document.write(byteArrayOutputStream);
OutputStream outputStream = new FileOutputStream(exportFile);
outputStream.write(byteArrayOutputStream.toByteArray());
byteArrayOutputStream.close();
in.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2下面來一張模板圖片
3 .進行word模板轉word以及輸出前端下載實現代碼
//3.1替換的值 k,v map
HashMap<String, Object> contentMap = new HashMap<String, Object>();
contentMap.put("${date}", this.projectVO.getDate());
//3.2 模板路徑
String fileName = "book.doc";
String pathIn = GboatAppContext.getWebRootPath() +"download" + "/" + fileName;
//3.3 生成文件路徑 String exportFile = "進場交易確認書.docx";
String pathOut= GboatAppContext.getWebRootPath() + "download" + "/" + exportFile;
//執行
DocUtil.getBuild(pathIn , contentMap, exportFile);
//4這段代碼是 頁面直接彈出下載生成的文件
InputStream inStream = new FileInputStream(pathOut);
response.setHeader("Content-Type", "application/octet-stream");
// 設置response的編碼方式
response.setContentType("application/x-msdownload");
String headers = request.getHeader("User-Agent").toUpperCase();
if (headers.contains("MSIE") || headers.contains("TRIDENT") || headers.contains("EDGE")) {
exportFile = URLEncoder.encode(exportFile, "utf-8");
// IE下載文件名空格變+號問題
exportFile = exportFile.replace("+", "%20");
} else {
exportFile = new String(exportFile.getBytes("utf-8"), "ISO8859-1");
}
// 設置附加文件名
response.setHeader("Content-Disposition", "attachment;filename=" + exportFile);
byte[] b = new byte[512];
int len;
ServletOutputStream outputStream = response.getOutputStream();
while ((len = inStream.read(b)) > 0) {
outputStream.write(b, 0, len);
}
inStream.close();
// 將寫入到客戶端的內存的數據,刷新到磁盤
outputStream.flush();
outputStream.close();
2 第二種帶圖片的word模板,只支持 docx的
2.1 工具類word模板工具類
import org.apache.poi.xwpf.usermodel.*;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 通過word模板生成新的word工具類
*/
public class WordUtils {
/**
* 根據模板生成word
* @param path 模板的路徑
* @param params 需要替換的參數
* @param tableList 需要插入的參數
* @param fileName 生成word文件的文件名
* @param response
*/
public void getWord(String path, Map<String, Object> params, String fileName, HttpServletResponse response) throws Exception {
File file = new File(path);
InputStream is = new FileInputStream(file);
CustomXWPFDocument doc = new CustomXWPFDocument(is);
this.replaceInPara(doc, params); //替換文本里面的變量
// this.replaceInTable(doc, params, tableList); //替換表格裏面的變量
//導出到文件
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
doc.write(byteArrayOutputStream);
OutputStream outputStream = new FileOutputStream(fileName);
outputStream.write(byteArrayOutputStream.toByteArray());
byteArrayOutputStream.close();
is.close();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 替換段落裏面的變量
* @param doc 要替換的文檔
* @param params 參數
*/
private void replaceInPara(CustomXWPFDocument doc, Map<String, Object> params) {
Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
XWPFParagraph para;
while (iterator.hasNext()) {
para = iterator.next();
this.replaceInPara(para, params, doc);
}
}
/**
* 替換段落裏面的變量
*
* @param para 要替換的段落
* @param params 參數
*/
private void replaceInPara(XWPFParagraph para, Map<String, Object> params, CustomXWPFDocument doc) {
List<XWPFRun> runs;
Matcher matcher;
if (this.matcher(para.getParagraphText()).find()) {
runs = para.getRuns();
int start = -1;
int end = -1;
String str = "";
for (int i = 0; i < runs.size(); i++) {
XWPFRun run = runs.get(i);
String runText = run.toString();
if ('$' == runText.charAt(0) && '{' == runText.charAt(1)) {
start = i;
}
if ((start != -1)) {
str += runText;
}
if ('}' == runText.charAt(runText.length() - 1)) {
if (start != -1) {
end = i;
break;
}
}
}
for (int i = start; i <= end; i++) {
para.removeRun(i);
i--;
end--;
}
for (Map.Entry<String, Object> entry : params.entrySet()) {
String key = entry.getKey();
if (str.indexOf(key) != -1) {
Object value = entry.getValue();
if (value instanceof String) {
str = str.replace(key, value.toString());
para.createRun().setText(str, 0);
break;
} else if (value instanceof Map) {
str = str.replace(key, "");
Map pic = (Map) value;
int width = Integer.parseInt(pic.get("width").toString());
int height = Integer.parseInt(pic.get("height").toString());
int picType = getPictureType(pic.get("type").toString());
byte[] byteArray = (byte[]) pic.get("content");
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray);
try {
//int ind = doc.addPicture(byteInputStream,picType);
//doc.createPicture(ind, width , height,para);
doc.addPictureData(byteInputStream, picType);
doc.createPicture(doc.getAllPictures().size() - 1, width, height, para);
para.createRun().setText(str, 0);
break;
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
}
/**
* 爲表格插入數據,行數不夠添加新行
*
* @param table 需要插入數據的表格
* @param tableList 插入數據集合
*/
private static void insertTable(XWPFTable table, List<String[]> tableList) {
//創建行,根據需要插入的數據添加新行,不處理表頭
for (int i = 0; i < tableList.size(); i++) {
XWPFTableRow row = table.createRow();
}
//遍歷表格插入數據
List<XWPFTableRow> rows = table.getRows();
int length = table.getRows().size();
for (int i = 1; i < length - 1; i++) {
XWPFTableRow newRow = table.getRow(i);
List<XWPFTableCell> cells = newRow.getTableCells();
for (int j = 0; j < cells.size(); j++) {
XWPFTableCell cell = cells.get(j);
String s = tableList.get(i - 1)[j];
cell.setText(s);
}
}
}
/**
* 替換表格裏面的變量
* @param doc 要替換的文檔
* @param params 參數
*/
private void replaceInTable(CustomXWPFDocument doc, Map<String, Object> params, List<String[]> tableList) {
Iterator<XWPFTable> iterator = doc.getTablesIterator();
XWPFTable table;
List<XWPFTableRow> rows;
List<XWPFTableCell> cells;
List<XWPFParagraph> paras;
while (iterator.hasNext()) {
table = iterator.next();
if (table.getRows().size() > 1) {
//判斷表格是需要替換還是需要插入,判斷邏輯有$爲替換,表格無$爲插入
if (this.matcher(table.getText()).find()) {
rows = table.getRows();
for (XWPFTableRow row : rows) {
cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
paras = cell.getParagraphs();
for (XWPFParagraph para : paras) {
this.replaceInPara(para, params, doc);
}
}
}
} else {
insertTable(table, tableList); //插入數據
}
}
}
}
/**
* 正則匹配字符串
*
* @param str
* @return
*/
private Matcher matcher(String str) {
Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
return matcher;
}
/**
* 根據圖片類型,取得對應的圖片類型代碼
*
* @param picType
* @return int
*/
private static int getPictureType(String picType) {
int res = CustomXWPFDocument.PICTURE_TYPE_PICT;
if (picType != null) {
if (picType.equalsIgnoreCase("png")) {
res = CustomXWPFDocument.PICTURE_TYPE_PNG;
} else if (picType.equalsIgnoreCase("dib")) {
res = CustomXWPFDocument.PICTURE_TYPE_DIB;
} else if (picType.equalsIgnoreCase("emf")) {
res = CustomXWPFDocument.PICTURE_TYPE_EMF;
} else if (picType.equalsIgnoreCase("jpg") || picType.equalsIgnoreCase("jpeg")) {
res = CustomXWPFDocument.PICTURE_TYPE_JPEG;
} else if (picType.equalsIgnoreCase("wmf")) {
res = CustomXWPFDocument.PICTURE_TYPE_WMF;
}
}
return res;
}
/**
* 將輸入流中的數據寫入字節數組
*
* @param in
* @return
*/
public static byte[] inputStream2ByteArray(InputStream in, boolean isClose) {
byte[] byteArray = null;
try {
int total = in.available();
byteArray = new byte[total];
in.read(byteArray);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (isClose) {
try {
in.close();
} catch (Exception e2) {
e2.getStackTrace();
}
}
}
return byteArray;
}
/**
* 關閉輸入流
*
* @param is
*/
private void close(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 關閉輸出流
*
* @param os
*/
private void close(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
這個有個問題就是 每一行只能有一個 值被替換 時候表格的那種帶圖片的模板
4 word轉pdf,最後還是找了 使用libreoffice來進行轉pdf 這種方式
注,將 word文件利用libreoffice的第三方插件來轉換
1代碼工具類1
package glodon.govp.cy.utils;
import java.io.File;
import java.io.IOException;
/**
* 使用libreoffice來進行轉pdf
*/
public class LibreOffice {
public static boolean wordConverterToPdf(String docxPath) throws IOException {
File file = new File(docxPath);
String path = file.getParent();
try {
String osName = System.getProperty("os.name");
String command = "";
if (osName.contains("Windows")) {
command = "cmd /c soffice --convert-to pdf -outdir " + docxPath + " " + path;
} else {
command = "libreoffice --headless --invisible --convert-to pdf:writer_pdf_Export " + docxPath + " --outdir " + path;
System.out.println("命令----------------------"+command+"-----------------------------");
}
boolean result = CommandExecute.executeLibreOfficeCommand(command);
return result;
} catch (Exception e) {
e.printStackTrace();
throw e;
}
}
2.代碼工具類2
package glodon.govp.cy.utils;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* linux或windows命令執行
*/
public class CommandExecute {
private static Logger logger = LoggerFactory.getLogger(CommandExecute.class);
public static void main(String[] args) {
// CommandExecute obj = new CommandExecute();
// String domainName = "www.baidu.com";
//in mac oxs
// String command = "ping " + domainName;
//in windows
//String command = "ping -n 3 " + domainName;
// String output = obj.executeCommand(command);
// System.out.println(output);
convertOffice2PDF("D:\\11.docx", "D:\\GBP");
}
public static String executeCommand(String command) {
StringBuffer output = new StringBuffer();
Process p;
InputStreamReader inputStreamReader = null;
BufferedReader reader = null;
try {
p = Runtime.getRuntime().exec(command);
p.waitFor();
inputStreamReader = new InputStreamReader(p.getInputStream(), "UTF-8");
reader = new BufferedReader(inputStreamReader);
String line = "";
while ((line = reader.readLine()) != null) {
output.append(line + "\n");
}
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(reader);
IOUtils.closeQuietly(inputStreamReader);
}
System.out.println(output.toString());
return output.toString();
}
/**
* 執行command指令
* @param command
* @return
*/
public static boolean executeLibreOfficeCommand(String command) {
logger.info("開始進行轉化.......");
Process process;// Process可以控制該子進程的執行或獲取該子進程的信息
try {
logger.debug("convertOffice2PDF cmd : {}", command);
process = Runtime.getRuntime().exec(command);// exec()方法指示Java虛擬機創建一個子進程執行指定的可執行程序,並返回與該子進程對應的Process對象實例。
// 下面兩個可以獲取輸入輸出流
// InputStream errorStream = process.getErrorStream();
// InputStream inputStream = process.getInputStream();
} catch (IOException e) {
logger.error(" convertOffice2PDF {} error", command, e);
return false;
}
int exitStatus = 0;
try {
exitStatus = process.waitFor();// 等待子進程完成再往下執行,返回值是子線程執行完畢的返回值,返回0表示正常結束
// 第二種接受返回值的方法
int i = process.exitValue(); // 接收執行完畢的返回值
logger.debug("i----" + i);
} catch (InterruptedException e) {
logger.error("InterruptedException convertOffice2PDF {}", command, e);
return false;
}
if (exitStatus != 0) {
logger.error("convertOffice2PDF cmd exitStatus {}", exitStatus);
} else {
logger.debug("convertOffice2PDF cmd exitStatus {}", exitStatus);
}
process.destroy(); // 銷燬子進程
logger.info("轉化結束.......");
return true;
}
/**
*
* soffice --headless --invisible --convert-to pdf:writer_pdf_Export D:/test/fb35e7d25afaf1b5d34f7bdb4f830c8c.doc --outdir D:/testfile2html
*
* @param srcPath
* @param desPath
* @return
* @throws NullPointerException
*/
public static boolean convertOffice2PDF(String srcPath, String desPath) throws NullPointerException{
System.out.println("開始進行轉化.....");
if(srcPath == null || desPath == null){
throw new NullPointerException("轉化文件不存在或者路徑有問題");
}
String command = "";
String osName = System.getProperty("os.name");
if (osName.contains("Windows")) {
command = "cmd /c soffice --headless --invisible --convert-to pdf:writer_pdf_Export " + srcPath + " --outdir " + desPath;
}
System.err.println(command + " : 轉化中....");
try {
Process p = Runtime.getRuntime().exec(command);
p.waitFor();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
} finally {
System.out.println("轉化結束...");
}
}
}
3word調用libreoffice工具類實現的轉換的代碼
public static void main(String[] args) {
try {
LibreOffice.wordConverterToPdf("D:\\11.docx");
} catch (IOException e) {
e.printStackTrace();
}
}
4.生成word模板2 及word轉pdf實現的代碼
public void downloadDetailsExcel() {
try {
// 下載
// 組織數據
initData();
String projectName = this.projectVO.getProjectName().replace(" ", "").trim();
String osName = System.getProperty("os.name");
String fileName = "book.docx";
String pathIn = GboatAppContext.getWebRootPath() +"download" + "/" + fileName;
String exportFile = projectName+"進場交易確認書.docx";//window的
if (!osName.contains("Windows")) {//linux的
exportFile = "進場交易確認書.docx";
}
String pathOut= GboatAppContext.getWebRootPath() + "download" + "/" + exportFile;
HashMap<String, Object> contentMap = new HashMap<String, Object>();
contentMap.put("${date}", this.projectVO.getDate());
contentMap.put("${project}", this.projectVO.getProcurementAgenter()+"組織的"
+projectName+"(項目編號爲:"+this.projectVO.getProjectCode()+")已於"
+this.projectVO.getDate()+"在北京市朝陽區公共資源交易平臺完成交易。");
Map<String,Object> header = new HashMap<String, Object>();
header.put("width", 150);
header.put("height", 150);
header.put("type", "jpg");
header.put("content", WordUtils.inputStream2ByteArray(CyAdmissionConfirmationAction.class.getClassLoader().getResourceAsStream("static/gongzhang.jpg"), true));
contentMap.put("${picture}",header);
//生成word
WordUtils utils = new WordUtils();
utils.getWord(pathIn, contentMap, pathOut, response);
//word轉pdf
if (!osName.contains("Windows")) {
exportFile = "進場交易確認書.docx";
pathOut= GboatAppContext.getWebRootPath() + "download" + "/" + exportFile;
}
LibreOffice.wordConverterToPdf(pathOut);
//輸出到頁面文件流
if (!osName.contains("Windows")) {
exportFile = "進場交易確認書.pdf";
pathOut= GboatAppContext.getWebRootPath() + "download" + "/" + exportFile;
}
InputStream inStream = new FileInputStream(pathOut);
response.setHeader("Content-Type", "application/octet-stream");
// 設置response的編碼方式
response.setContentType("application/x-msdownload");
String headers = request.getHeader("User-Agent").toUpperCase();
if (headers.contains("MSIE") || headers.contains("TRIDENT") || headers.contains("EDGE")) {
exportFile = URLEncoder.encode(exportFile, "utf-8");
// IE下載文件名空格變+號問題
exportFile = exportFile.replace("+", "%20");
} else {
exportFile = new String(exportFile.getBytes("utf-8"), "ISO8859-1");
}
// 設置附加文件名
response.setHeader("Content-Disposition", "attachment;filename=" + exportFile);
byte[] b = new byte[512];
int len;
ServletOutputStream outputStream = response.getOutputStream();
while ((len = inStream.read(b)) > 0) {
outputStream.write(b, 0, len);
}
inStream.close();
// 將寫入到客戶端的內存的數據,刷新到磁盤
outputStream.flush();
outputStream.close();
//更新評價狀態 是否下載了進場交易確認書
ArrivalEvaluation arrivalEvaluation =confirmationBusiness.getArrivalEvaluationByProjectId(projectId);
if(null != arrivalEvaluation && !"2".equals(arrivalEvaluation.getDownloadStatus())){
arrivalEvaluation.setDownloadStatus("2");
confirmationBusiness.update(arrivalEvaluation);
}
} catch (Exception e) {
GboatAppContext.output(JsonResult.createFailure(e.getMessage()));
}
}
使用libreoffice來進行轉pdf 這種方式需要安裝的軟件
可以參考以下的連接 ;轉
鏈接: [https://blog.csdn.net/eclothy/article/details/84938807]
最後付一下maven依賴:是word模板的
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>3.15</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.9</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>2.4</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
當報錯時 Error: source file could not be loaded
解決時,應該 在執行語句上加上版本號
libreoffice --headless --invisible --convert-to pdf:writer_pdf_Export " + docxPath + " --outdir " + path;
用着這一方式可以加載到文件
libreoffice6.1 --headless --invisible --convert-to pdf:writer_pdf_Export " + docxPath + " --outdir " + path;