已经实践两种方法,第一种用doc模板 生成的时候替换模板中需要替换的内容,再讲替换好的doc转换成pdf。
第二种生成html页面将页面转pdf,这种更直观,所见即所得。
第一种需要定制模板,然后生成pdf下载打印。因为模板有可能随时改动,样式内容都可以发生变化。所以我这边在用doc做模板,先将变量替换进去,生成新的doc 再讲新的doc转换为pdf让用户下载。随时可以修改模板 ,不要需要修改代码,导出的pdf就会自动跟着改动。
doc替换文字用的网上找的别人的方法。
用模板和数据替换生成新的doc
public void toWord(String infilePath, String outfilePath, Map<String, Object> map) {
File intfile = new File(infilePath);
FileInputStream fileInputStream = null;
File outfile = new File(outfilePath);
FileOutputStream out;
try {
fileInputStream = new FileInputStream(intfile);
template = new WordTemplate(fileInputStream);
template.replaceTag(map);// 鏇挎崲瀛楃涓叉ā鐗�
out = new FileOutputStream(outfile);
BufferedOutputStream bos = new BufferedOutputStream(out);
template.write(bos);
} catch (IOException exception) {
exception.printStackTrace();
}
}
下面的代码是替换的代码,需要poi-3.16.jar,poi-ooxml-3.15.jar,poi-ooxml-schemas-3.15.jar,poi-scratchpad-3.16.jar,poi-tl-0.0.3.jar,注意下版本,我在这里踩了坑 有的版本会影响到原有处理excel的功能 ,有的会导致pdf 没法导出。
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import org.apache.poi.xwpf.usermodel.XWPFTable;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTbl;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblPr;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.CTTblWidth;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STJc;
import org.openxmlformats.schemas.wordprocessingml.x2006.main.STTblWidth;
public class WordTemplate {
private XWPFDocument document;
public WordTemplate(InputStream inputStream) throws IOException {
document = new XWPFDocument(inputStream);
}
public void replaceTag(Map<String, Object> map) {
for (Entry<String, Object> item : map.entrySet()) {
if (item.getKey().equals("String")) {// 鐩爣涓烘枃鏈�
Map<String, String> tempMap = (Map<String, String>) item.getValue();
replaceParagraphs(tempMap);
replaceTables(tempMap);
} else if (item.getKey().equals("Table")) {// 鐩爣涓鸿〃鏍�
replaceKeyToTables((Map<String, Object>) item.getValue());
}
}
}
public void write(OutputStream outputStream) throws IOException {
document.write(outputStream);
}
/**
* 鏇挎崲娈佃惤閲岀殑淇℃伅顒�
*
* @param map
*/
private void replaceParagraphs(Map<String, String> map) {
List<XWPFParagraph> allXWPFParagraphs = document.getParagraphs();
for (XWPFParagraph XwpfParagrapg : allXWPFParagraphs) {
XWPFParagraphHandler XwpfParagrapgUtils = new XWPFParagraphHandler(XwpfParagrapg);
XwpfParagrapgUtils.replaceAll(map);
}
}
/**
* 鏇挎崲琛ㄦ牸閲岀殑淇℃伅顒�
*
* @param map
*/
private void replaceTables(Map<String, String> map) {
List<XWPFTable> xwpfTables = document.getTables();
for (XWPFTable xwpfTable : xwpfTables) {
XWPFTableHandler xwpfTableUtils = new XWPFTableHandler(xwpfTable);
xwpfTableUtils.replace(map);
}
}
/**
* 鏇挎崲琛ㄦ牸
*
* @author huangdongkui
* @param map
*/
public void replaceKeyToTables(Map<String, Object> param) {
List<XWPFParagraph> paragraphList = document.getParagraphs();
if (paragraphList != null && paragraphList.size() > 0) {
for (XWPFParagraph paragraph : paragraphList) {
String text = paragraph.getParagraphText();
for (Entry<String, Object> entry : param.entrySet()) {
String key = entry.getKey();
if (text.indexOf(key) != -1) {
Object value = entry.getValue();
if (value instanceof List) {// 琛ㄦ牸
text = text.replace(key, "");
XWPFTable tableOne = document.insertNewTbl(paragraph.getCTP().newCursor());
//娣诲姞鍒�
for (int col = 1; col < ((Map<String, String>) ((List) value).get(0)).entrySet().size(); col++) {
tableOne.addNewCol();
}
// 濉厖鍒楀ご
XWPFTableRow crow = tableOne.createRow();
int k = 0;
for (Entry<String, String> col : ((Map<String, String>) ((List) value).get(0)).entrySet()) {
String skey = col.getKey();
if (skey!=null&&!skey.equals("")) {
crow.getCell(k).setText(skey);
k++;
}
}
for (int i = 1; i < ((List) value).size(); i++) {
// 娣诲姞琛�
XWPFTableRow rrow = tableOne.createRow();
int j = 0;
for (Entry<String, String> col : ((Map<String, String>) ((List) value).get(i)).entrySet()) {
String sValue = col.getValue();
if (sValue!=null&&!sValue.equals("")) {
rrow.getCell(j).setText(sValue);
j++;
}
}
}
tableOne.removeRow(0);
setTableWidthAndHAlign(tableOne, "8000", STJc.CENTER);
}
List<XWPFRun> runs = paragraph.getRuns();
for (XWPFRun xwpfrun : runs) {
xwpfrun.setText("", 0);
}
}
}
}
}
}
public void setTableWidthAndHAlign(XWPFTable table, String width, STJc.Enum enumValue) {
CTTblPr tblPr = getTableCTTblPr(table);
CTTblWidth tblWidth = tblPr.isSetTblW() ? tblPr.getTblW() : tblPr.addNewTblW();
if (enumValue != null) {
CTJc cTJc = tblPr.addNewJc();
cTJc.setVal(enumValue);
}
tblWidth.setW(new BigInteger(width));
tblWidth.setType(STTblWidth.DXA);
}
/**
* @Description: 寰楀埌Table鐨凜TTblPr,涓嶅瓨鍦ㄥ垯鏂板缓
*/
public CTTblPr getTableCTTblPr(XWPFTable table) {
CTTbl ttbl = table.getCTTbl();
CTTblPr tblPr = ttbl.getTblPr() == null ? ttbl.addNewTblPr() : ttbl.getTblPr();
return tblPr;
}
}
生成doc没有问题之后 转换pdf ,用到jar 有org.apache.poi.xwpf.converter.core-1.0.4.jar,org.apache.poi.xwpf.converter.pdf-1.0.4.jar
template = "c:/合同模板/"+categoryCode+".docx";
WordTemplateUtilities.GetInstance().toWord(template, outfilePath, map);
String pdfPath = filePath + UUID.randomUUID() + ".pdf";
WordTemplateUtilities.GetInstance().convertWordToPdf(outfilePath, pdfPath);
return pdfPath;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.xwpf.converter.pdf.PdfConverter;
import org.apache.poi.xwpf.converter.pdf.PdfOptions;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
public class WordTemplateUtilities {
public static void convertWordToPdf(String wordPath, String pdfPath) throws IOException {
FileInputStream inpuFile = new FileInputStream(wordPath);
File outFile=new File(pdfPath);
//从输入的文件流创建对象
XWPFDocument document = new XWPFDocument(inpuFile);
//创建PDF选项
PdfOptions pdfOptions = PdfOptions.create();//.fontEncoding("windows-1250")
//为输出文件创建目录
outFile.getParentFile().mkdirs();
//执行PDF转化
PdfConverter.getInstance().convert(document, new FileOutputStream(outFile), pdfOptions);
System.out.println("成功转换:"+pdfPath);
}
}
第二种 过两天在写