java将docx文件转成pdf文件的实现方法,需要的jar包下载地址:https://download.csdn.net/download/keke921231/10529672
1.读写docx文件。
需要读写docx文件需要用到poi包,等下会提供下载地址,在读写docx文件之前,需要对docx文件进行操作,打开docx文件后,再需要编辑的地方加上“:${key}”,再在java文件中通过map来对这个值进行编辑,比如map.put(key,value)
docx文件内操作(注意“:”这个符号是中文的,“${}”符号是英文的):
编号:${id}
甲方(借款人):___${jiaName}__________________
身份证号/统一社会信用代码:${jiaIDCard}
住所:${jarAddress}
通讯地址:${jarAddr}
乙方(出借人):${yiName}
身份证号/统一社会信用代码:${yiIDCard}
住所:${yiAddress}
通讯地址:${yiAddr}
java文件中map的操作:
Map params = new HashMap();
params.put("id", "测试编号" );
params.put("jiaName", "甲方名称");
params.put("jiaIDCard", "甲方id号");
params.put("jarAddress", "甲方住宿");
params.put("jarAddr", "甲方地址");
params.put("yiName", "乙方名称");
params.put("yiIDCard", "乙方id号");
params.put("yiAddress", "乙方住宿地址");
params.put("yiAddr", "乙方地址");
有这两个后,接下来是将docx文件中的key,value进行替换
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.poi.xwpf.extractor.XWPFWordExtractor;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.apache.poi.xwpf.usermodel.XWPFRun;
import topdf.StrToPDF;
public class InputDocx {
private static InputDocx inputDocx;
public static InputDocx getInputDocx() {
if (inputDocx == null)
inputDocx = new InputDocx();
return inputDocx;
}
public String DocxToString(Map params, String wordUrl) {
XWPFDocument doc = valueInputWord(params, wordUrl);
if (doc == null)return "";
return new XWPFWordExtractor(doc).getText();
}
public XWPFDocument valueInputWord(Map params, String wordUrl) {
XWPFDocument doc;// word文档对象
try {
InputStream in_stream = new FileInputStream(wordUrl);// 文件流
doc = new XWPFDocument(in_stream);
replaceInPara(doc, params);
// OutputStream os = new FileOutputStream("E:\\writejiekuanxieyi.docx");
// doc.write(os);
closeStream(in_stream);
// closeStream(os);
return doc;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
/**
* 关闭输入流
*
* @param is
*/
private void closeStream(InputStream is) {
if (is != null) {
try {
is.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 关闭输出流
*
* @param os
*/
private void closeStream(OutputStream os) {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
/**
* 替换段落里面的变量
*
* @param doc
* 要替换的文档
* @param params
* 参数
*/
private void replaceInPara(XWPFDocument doc, Map params) {
Iterator iterator = doc.getParagraphsIterator();
XWPFParagraph para;
while (iterator.hasNext()) {
para = iterator.next();
replaceInPara(para, params);
}
}
/**
* 替换段落里面的变量
*
* @param para
* 要替换的段落
* @param params
* 参数
*/
private void replaceInPara(XWPFParagraph para, Map params) {
List runs;
Matcher matcher;
System.out.println("para::" + para.getParagraphText());
if (matcher(para.getParagraphText()).find()) {
runs = para.getRuns();
for (int i = 0; i < runs.size(); i++) {
XWPFRun run = runs.get(i);
String runText = run.toString();
System.out.println("runText:1:" + runText);
matcher = matcher(runText);
if (matcher.find()) {
while ((matcher = matcher(runText)).find()) {
runText = matcher.replaceFirst(String.valueOf(params.get(matcher.group(1))));
System.out.println("runText::" + runText);
}
// 直接调用XWPFRun的setText()方法设置文本时,在底层会重新创建一个XWPFRun,把文本附加在当前文本后面,
// 所以我们不能直接设值,需要先删除当前run,然后再自己手动插入一个新的run。
para.removeRun(i);
para.insertNewRun(i).setText(runText);
}
}
}
}
/**
* 正则匹配字符串
*
* @param str
* @return
*/
private Matcher matcher(String str) {
Pattern pattern = Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
Matcher matcher = pattern.matcher(str);
return matcher;
}
}
2.创建DocxToPdf类,写将XWPFDocument对象转成pdf文件的方法
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
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 DocxToPdf {
public static void docxToPdf( XWPFDocument document,String outUrl ) throws Exception {
OutputStream outStream=getOutFileStream(outUrl);
PdfOptions options = PdfOptions.create();
PdfConverter.getInstance().convert(document, outStream, options);
}
protected static OutputStream getOutFileStream(String outputFilePath) throws IOException{
File outFile = new File(outputFilePath);
try{
//Make all directories up to specified
outFile.getParentFile().mkdirs();
} catch (NullPointerException e){
//Ignore error since it means not parent directories
}
outFile.createNewFile();
FileOutputStream oStream = new FileOutputStream(outFile);
return oStream;
}
}
3.将docx文件转成PDF文件的方法
public static void main(String[] args) {
Map params = new HashMap();
params.put("id", "测试编号" );
params.put("jiaName", "甲方名称");
params.put("jiaIDCard", "甲方id号");
params.put("jarAddress", "甲方住宿");
params.put("jarAddr", "甲方地址");
params.put("yiName", "乙方名称");
params.put("yiIDCard", "乙方id号");
params.put("yiAddress", "乙方住宿地址");
params.put("yiAddr", "乙方地址");
XWPFDocument xWPFDocument= InputDocx.getInputDocx().valueInputWord(params, "E:\\jiekuanxieyi.docx");
try {
DocxToPdf.docxToPdf(xWPFDocument, "E:\\writejiekuanxieyi.pdf");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
4.需要的jar包