Java 讀寫docx檔案後直接轉成PDF檔案方法
阿新 • • 發佈:2019-02-17
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<String, Object> params = new HashMap<String, Object>(); 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<String, Object> params, String wordUrl) { XWPFDocument doc = valueInputWord(params, wordUrl); if (doc == null)return ""; return new XWPFWordExtractor(doc).getText(); } public XWPFDocument valueInputWord(Map<String, Object> 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<String, Object> params) { Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator(); XWPFParagraph para; while (iterator.hasNext()) { para = iterator.next(); replaceInPara(para, params); } } /** * 替換段落裡面的變數 * * @param para * 要替換的段落 * @param params * 引數 */ private void replaceInPara(XWPFParagraph para, Map<String, Object> params) { List<XWPFRun> 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<String, Object> params = new HashMap<String, Object>();
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包