java 編碼填充 word 模板生成 word合同,並將word合同轉成pdf 文件
java 編碼填充 word 模板生成 word合同,並將word合同轉成pdf 文件
一、
1、
package com.test;
import java.io.IOException;
import java.io.InputStream;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.apache.poi.xwpf.usermodel.XWPFParagraph;
import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
import org.openxmlformats.schemas.drawingml.x2006.main.CTPositiveSize2D;
import org.openxmlformats.schemas.drawingml.x2006.wordprocessingDrawing.CTInline;
import org.apache.xmlbeans.*;
/**
* 自定義 XWPFDocument,並重寫 createPicture()方法
* 重寫的類 CustomXWPFDocument
*/
public class CustomXWPFDocument extends XWPFDocument {
public CustomXWPFDocument(InputStream in) throws IOException {
super(in);
}
public CustomXWPFDocument() {
super();
}
public CustomXWPFDocument(OPCPackage pkg) throws IOException {
super(pkg);
}
/**
* @param id
* @param width 寬
* @param height 高
* @param paragraph 段落
*/
public void createPicture(int id, int width, int height,XWPFParagraph paragraph) {
final int EMU = 9525;
width *= EMU;
height *= EMU;
String blipId = getAllPictures().get(id).getPackageRelationship().getId();
CTInline inline = paragraph.createRun().getCTR().addNewDrawing().addNewInline();
String picXml = ""
+ "<a:graphic xmlns:a=\"http://schemas.openxmlformats.org/drawingml/2006/main\">"
+ " <a:graphicData uri=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
+ " <pic:pic xmlns:pic=\"http://schemas.openxmlformats.org/drawingml/2006/picture\">"
+ " <pic:nvPicPr>" + " <pic:cNvPr id=\""
+ id
+ "\" name=\"Generated\"/>"
+ " <pic:cNvPicPr/>"
+ " </pic:nvPicPr>"
+ " <pic:blipFill>"
+ " <a:blip r:embed=\""
+ blipId
+ "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"
+ " <a:stretch>"
+ " <a:fillRect/>"
+ " </a:stretch>"
+ " </pic:blipFill>"
+ " <pic:spPr>"
+ " <a:xfrm>"
+ " <a:off x=\"0\" y=\"0\"/>"
+ " <a:ext cx=\""
+ width
+ "\" cy=\""
+ height
+ "\"/>"
+ " </a:xfrm>"
+ " <a:prstGeom prst=\"rect\">"
+ " <a:avLst/>"
+ " </a:prstGeom>"
+ " </pic:spPr>"
+ " </pic:pic>"
+ " </a:graphicData>" + "</a:graphic>";
inline.addNewGraphic().addNewGraphicData();
XmlToken xmlToken = null;
try {
xmlToken = XmlToken.Factory.parse(picXml);
} catch (XmlException xe) {
xe.printStackTrace();
}
inline.set(xmlToken);
inline.setDistT(0);
inline.setDistB(0);
inline.setDistL(0);
inline.setDistR(0);
CTPositiveSize2D extent = (CTPositiveSize2D) inline.addNewExtent();
extent.setCx(width);
extent.setCy(height);
CTNonVisualDrawingProps docPr = inline.addNewDocPr();
docPr.setId(id);
docPr.setName("圖片" + id);
docPr.setDescr("測試");
}
}
2、
package com.test;
import java.util.Date;
import java.util.concurrent.Callable;
public class MyCallable implements Callable<Object> {
private String taskNum;
public MyCallable(String taskNum) {
this.taskNum = taskNum;
}
public Object call() throws Exception {
System.out.println(">>>" + taskNum + "任務啟動");
Date dateTmp1 = new Date();
Thread.sleep(3000);
Date dateTmp2 = new Date();
long time = dateTmp2.getTime() - dateTmp1.getTime();
System.out.println(">>>" + taskNum + "任務終止");
return taskNum + "任務返回執行結果,當前任務時間【" + time + "毫秒】";
}
}
3、
package com.test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
public class mythred {
public void WordRun(int i) throws Throwable{
Map<String, Object> param = new HashMap<String, Object>();
param.put("${name}", "金正恩");
param.put("${profession}", "特戰組");
param.put("${sex}", "男");
param.put("${school_name}", "中國國防大學");
param.put("${twocode}", "遺留問題");
param.put("${header}", "風控預防針");
param.put("${date}", new Date().toString());
CustomXWPFDocument doc = WordUtil.generateWord(param, "c://mouth.docx");
FileOutputStream fopts = new FileOutputStream("c:/"+i+".docx");
doc.write(fopts);
fopts.close();
//Thread.sleep(20000);
System.out.println("模板生成");
}
}
4、
package com.test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.*;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.ArrayList;
import java.util.Map;
/**
* 有返回值的執行緒
*/
@SuppressWarnings("unchecked")
public class Test {
public void PrintWord(final ArrayList<String> li, final Map<String,Object> map) throws Throwable, Throwable{
System.out.println("----程式開始執行----");
Date date1 = new Date();
int taskSize = 1;
// 建立一個執行緒池
ExecutorService pool = Executors.newFixedThreadPool(taskSize);
//建立快取執行緒池,根據任務來自動建立執行緒的數量,可以完成建立的所有任務
// ExecutorService threadPool = Executors.newCachedThreadPool();
// 建立多個有返回值的任務
List<Future> list = new ArrayList<Future>();
for (int i=0; i < taskSize; i++) {
Callable c = new MyCallable(i+" ");
// 執行任務並獲取Future物件
// Future f = pool.submit(c);
Future f = pool.submit(c);
final int task = i;
pool.execute(new Runnable() {
@Override
public void run() {
for(int j=0;j<=task;j++){
System.out.println(Thread.currentThread().getName()
+" is looping of "+ j+" for task of " +task);
Map<String, Object> param = new HashMap<String, Object>();
param.put("{借款人姓名/公司名稱}", "金正恩00000000000");
param.put("{每月還款額}", "金正恩4354654");
param.put("{還款日}", "金正恩66666666666");
// //param.put("公司名稱}", "朝鮮統戰部");
// param.put("{出借人姓名/公司名稱}", "金日成");
// param.put("{公司名稱}", "朝鮮指揮部");
// param.put("{當前年}", "遺留問題");
// param.put("${header}", "風控預防針");
// param.put("${date}", new Date().toString());
try {//c://mouth.docx
//for(int k=0;k<li.size();k++){
CustomXWPFDocument doc = WordUtil.generateWord(param,"c:/555.docx");
FileOutputStream fopts;
String gpsCopy= "c:/"+task+".docx";
fopts = new FileOutputStream(gpsCopy);
doc.write(fopts);
fopts.close();
//word conver pdf
WordConverPdf.word2pdf("c:/"+task+".docx");
//}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
});
list.add(f);
}
// 關閉執行緒池
// pool.shutdown();
//等任務完成後
pool.shutdown();
// 獲取所有併發任務的執行結果
for (Future f : list) {
// 從Future物件上獲取任務的返回值,並輸出到控制檯
System.out.println(">>>" + f.get().toString());
}
Date date2 = new Date();
System.out.println("----程式結束執行----,程式執行時間【"
+ (date2.getTime() - date1.getTime()) + "毫秒】");
}
public static void main(String[] args)
{
// Test t=new Test();
// String gps="c://GPS免責宣告書.docx";
//
// t.PrintWord(gps);
ArrayList<String> list = new ArrayList<String>(){{add("c://oop.docx"); add("c://oop1.docx");}};
Map<String,Object> map =new HashMap<String,Object>();
map.put("{甲方}","上海寶富第三方支付");
map.put("{乙方}","乙方");
Test t=new Test();
try {
t.PrintWord(list, map);
System.out.println("success");
} catch (Throwable e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
5.
package com.test;
import java.io.File;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.xwpf.usermodel.XWPFDocument;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.io.SAXReader;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
public class Word2pdf {
static final int wdFormatPDF = 17;// PDF 格式
public int wordToPDF(String sfileName,String toFileName) throws Exception{
System.out.println("啟動Word...");
long start = System.currentTimeMillis();
ActiveXComponent app = null;
Dispatch doc = null;
try {
app = new ActiveXComponent("Word.Application");
// 設定word不可見
app.setProperty("Visible", new Variant(false));
// 開啟word檔案
Dispatch docs = app.getProperty("Documents").toDispatch();
// doc = Dispatch.call(docs, "Open" , sourceFile).toDispatch();
doc = Dispatch.invoke(docs,"Open",Dispatch.Method,new Object[] {
sfileName, new Variant(false),new Variant(true) }, new int[1]).toDispatch();
System.out.println("開啟文件..." + sfileName);
System.out.println("轉換文件到PDF..." + toFileName);
File tofile = new File(toFileName);
// System.err.println(getDocPageSize(new File(sfileName)));
if (tofile.exists()) {
tofile.delete();
}
// Dispatch.call(doc, "SaveAs", destFile, 17);
// 作為html格式儲存到臨時檔案::引數 new Variant(8)其中8表示word轉html;7表示word轉txt;44表示Excel轉html;17表示word轉成pdf。。
Dispatch.invoke(doc, "SaveAs", Dispatch.Method, new Object[] {
toFileName, new Variant(17) }, new int[1]);
long end = System.currentTimeMillis();
System.out.println("轉換完成..用時:" + (end - start) + "ms.");
} catch (Exception e) {
e.printStackTrace();
System.out.println("========Error:文件轉換失敗:" + e.getMessage());
}catch(Throwable t){
t.printStackTrace();
} finally {
// 關閉word
Dispatch.call(doc,"Close",false);
System.out.println("關閉文件");
if (app != null)
app.invoke("Quit", new Variant[] {});
}
//如果沒有這句話,winword.exe程序將不會關閉
ComThread.Release();
return 1;
}
private static Document read(File xmlFile) throws DocumentException {
SAXReader saxReader = new SAXReader();
return saxReader.read(xmlFile);
}
// public String getDocPageSize(File file){
// String pages = null;
// try{
// Document doc = read(file);
// List<Node> nodes = doc.selectNodes("//o:Pages");
// if(nodes != null && nodes.size() > 0){
// pages = nodes.get(0).getText();
// System.out.println("/////////////////");
// System.out.println("該word文件的頁數為:"+Integer.parseInt(pages));
// System.out.println("/////////////////");
// }else{
// System.out.println("*********");
// System.out.println("頁面轉換錯誤");
// System.out.println("*********");
// }
// }catch(Exception ex){
// ex.printStackTrace();
// }
// return pages;
// }
public int getDocPageSize(String filePath) throws Exception {
XWPFDocument docx = new XWPFDocument(POIXMLDocument.openPackage(filePath));
int pages = docx.getProperties().getExtendedProperties().getUnderlyingProperties().getPages();//總頁數
int wordCount = docx.getProperties().getExtendedProperties().getUnderlyingProperties().getCharacters();// 忽略空格的總字元數 另外還有getCharactersWithSpaces()方法獲取帶空格的總字數。
System.out.println ("pages=" + pages + " wordCount=" + wordCount);
return pages;
}
public static void main(String[] args) throws Exception {
Word2pdf d = new Word2pdf();
System.err.println(d.getDocPageSize("c:\\mouth.docx"));
d.wordToPDF("c:\\mouth.docx", "d:\\law.pdf");
}
}
6、
package com.test;
import java.io.File;
import java.io.IOException;
import java.util.regex.Pattern;
import org.artofsolving.jodconverter.OfficeDocumentConverter;
import org.artofsolving.jodconverter.office.DefaultOfficeManagerConfiguration;
import org.artofsolving.jodconverter.office.OfficeManager;
public class WordConverPdf {
public static void word2pdf(String inputFilePath) {
DefaultOfficeManagerConfiguration config = new DefaultOfficeManagerConfiguration();
String officeHome = getOfficeHome();
config.setOfficeHome(officeHome);
OfficeManager officeManager = config.buildOfficeManager();
officeManager.start();
OfficeDocumentConverter converter = new OfficeDocumentConverter(officeManager);
String outputFilePath = getOutputFilePath(inputFilePath);
File inputFile = new File(inputFilePath);
if (inputFile.exists()) {// 找不到原始檔, 則返回
File outputFile = new File(outputFilePath);
if (!outputFile.getParentFile().exists()) { // 假如目標路徑不存在, 則新建該路徑
outputFile.getParentFile().mkdirs();
}
converter.convert(inputFile, outputFile);
}
officeManager.stop();
}
public static String getOutputFilePath(String inputFilePath) {
String outputFilePath = inputFilePath.replaceAll(".docx", ".pdf");
return outputFilePath;
}
public static String getOfficeHome() {
String osName = System.getProperty("os.name");
if (Pattern.matches("Linux.*", osName)) {
return "/opt/openoffice.org3";
} else if (Pattern.matches("Windows.*", osName)) {
return "C:/Program Files (x86)/OpenOffice 4";
} else if (Pattern.matches("Mac.*", osName)) {
return "/Application/OpenOffice.org.app/Contents";
}
return null;
}
}
7、
package com.test;
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.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
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.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
public class WordPOI {
// 返回Docx中需要替換的特殊字元,沒有重複項
// 推薦傳入正則表示式引數"\\$\\{[^{}]+\\}"
public ArrayList<String> getReplaceElementsInWord(String filePath,
String regex) {
String[] p = filePath.split("\\.");
if (p.length > 0) {// 判斷檔案有無副檔名
// 比較副檔名
if (p[p.length - 1].equalsIgnoreCase("doc")) {
ArrayList<String> al = new ArrayList<>();
File file = new File(filePath);
HWPFDocument document = null;
try {
InputStream is = new FileInputStream(file);
document = new HWPFDocument(is);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
Range range = document.getRange();
String rangeText = range.text();
CharSequence cs = rangeText.subSequence(0, rangeText.length());
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(cs);
int startPosition = 0;
while (matcher.find(startPosition)) {
if (!al.contains(matcher.group())) {
al.add(matcher.group());
}
startPosition = matcher.end();
}
return al;
} else if (p[p.length - 1].equalsIgnoreCase("docx")) {
ArrayList<String> al = new ArrayList<>();
XWPFDocument document = null;
try {
document = new XWPFDocument(
POIXMLDocument.openPackage(filePath));
} catch (IOException e) {
e.printStackTrace();
}
// 遍歷段落
Iterator<XWPFParagraph> itPara = document
.getParagraphsIterator();
while (itPara.hasNext()) {
XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
String paragraphString = paragraph.getText();
CharSequence cs = paragraphString.subSequence(0,
paragraphString.length());
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(cs);
int startPosition = 0;
while (matcher.find(startPosition)) {
if (!al.contains(matcher.group())) {
al.add(matcher.group());
}
startPosition = matcher.end();
}
}
// 遍歷表
Iterator<XWPFTable> itTable = document.getTablesIterator();
while (itTable.hasNext()) {
XWPFTable table = (XWPFTable) itTable.next();
int rcount = table.getNumberOfRows();
for (int i = 0; i < rcount; i++) {
XWPFTableRow row = table.getRow(i);
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
String cellText = "";
cellText = cell.getText();
CharSequence cs = cellText.subSequence(0,
cellText.length());
Pattern pattern = Pattern.compile(regex);
Matcher matcher = pattern.matcher(cs);
int startPosition = 0;
while (matcher.find(startPosition)) {
if (!al.contains(matcher.group())) {
al.add(matcher.group());
}
startPosition = matcher.end();
}
}
}
}
return al;
} else {
return null;
}
} else {
return null;
}
}
// 替換word中需要替換的特殊字元
public static boolean replaceAndGenerateWord(String srcPath,
String destPath, Map<String, String> map) {
String[] sp = srcPath.split("\\.");
String[] dp = destPath.split("\\.");
if ((sp.length > 0) && (dp.length > 0)) {// 判斷檔案有無副檔名
// 比較副檔名
if (sp[sp.length - 1].equalsIgnoreCase("docx")) {
try {
XWPFDocument document = new XWPFDocument(
POIXMLDocument.openPackage(srcPath));
// 替換段落中的指定文字
Iterator<XWPFParagraph> itPara = document
.getParagraphsIterator();
while (itPara.hasNext()) {
XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
List<XWPFRun> runs = paragraph.getRuns();
for (int i = 0; i < runs.size(); i++) {
String oneparaString = runs.get(i).getText(
runs.get(i).getTextPosition());
for (Map.Entry<String, String> entry : map
.entrySet()) {
oneparaString = oneparaString.replace(
entry.getKey(), entry.getValue());
}
runs.get(i).setText(oneparaString, 0);
}
}
// 替換表格中的指定文字
Iterator<XWPFTable> itTable = document.getTablesIterator();
while (itTable.hasNext()) {
XWPFTable table = (XWPFTable) itTable.next();
int rcount = table.getNumberOfRows();
for (int i = 0; i < rcount; i++) {
XWPFTableRow row = table.getRow(i);
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
String cellTextString = cell.getText();
for (Entry<String, String> e : map.entrySet()) {
if (cellTextString.contains(e.getKey()))
cellTextString = cellTextString
.replace(e.getKey(),
e.getValue());
}
cell.removeParagraph(0);
cell.setText(cellTextString);
}
}
}
FileOutputStream outStream = null;
outStream = new FileOutputStream(destPath);
document.write(outStream);
outStream.close();
return true;
} catch (Exception e) {
e.printStackTrace();
return false;
}
} else
// doc只能生成doc,如果生成docx會出錯
if ((sp[sp.length - 1].equalsIgnoreCase("doc"))
&& (dp[dp.length - 1].equalsIgnoreCase("doc"))) {
HWPFDocument document = null;
try {
document = new HWPFDocument(new FileInputStream(srcPath));
Range range = document.getRange();
for (Map.Entry<String, String> entry : map.entrySet()) {
range.replaceText(entry.getKey(), entry.getValue());
}
FileOutputStream outStream = null;
outStream = new FileOutputStream(destPath);
document.write(outStream);
outStream.close();
return true;
} catch (FileNotFoundException e) {
e.printStackTrace();
return false;
} catch (IOException e) {
e.printStackTrace();
return false;
}
} else {
return false;
}
} else {
return false;
}
}
public static void main(String[] args) {
// TODO Auto-generated method stub
String filepathString = "D:/2.doc";
String destpathString = "D:/2ttt.doc";
Map<String, String> map = new HashMap<String, String>();
map.put("${NAME}", "王五王五啊王力巨集的辣味回答侯衛東拉網");
map.put("${NsAME}", "王五王五啊王力味回答侯衛東拉網");
map.put("${NAMaE}", "王五王五啊王力巨集侯衛東拉網");
map.put("${NArME}", "王五王五啊王力巨集的辣味回答東拉網");
map.put("${NwAME}", "王五王五啊王的辣味回答侯衛東拉網");
map.put("${NA4ME}", "王五王五啊王力侯衛東拉網");
map.put("${N5AME}", "王五王五辣味回答侯衛東拉網");
map.put("${NAadwME}", "王五力巨集的辣味回答侯衛東拉網");
System.out.println(replaceAndGenerateWord(filepathString,
destpathString, map));
}
}
8、
package com.test;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.openxml4j.opc.OPCPackage;
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.XWPFTableCell;
import org.apache.poi.xwpf.usermodel.XWPFTableRow;
/**
* 適用於word 2007
* poi 版本 3.7
*/
public class WordUtil {
/** 臨時存放要替換的元素
*/
private static List<XWPFRun> tempRuns =new ArrayList<XWPFRun>();
/** 臨時存放要替換的元素的文字
*/
private static List<String> tempRunTexts =new ArrayList<String>();
/**
* 封裝的工具類WordUtil.java
* 根據指定的引數值、模板,生成 word 文件
* @param param 需要替換的變數
* @param template 模板
*/
public static CustomXWPFDocument generateWord(Map<String, Object> param, String
template) {
CustomXWPFDocument doc = null;
try {
OPCPackage pack = POIXMLDocument.openPackage(template);
doc = new CustomXWPFDocument(pack);
if (param != null && param.size() > 0) {
//處理段落
List<XWPFParagraph> paragraphList = doc.getParagraphs();
processParagraphs(paragraphList, param, doc);
//處理表格
Iterator<XWPFTable> it = doc.getTablesIterator();
while (it.hasNext()) {
XWPFTable table = it.next();
List<XWPFTableRow> rows = table.getRows();
for (XWPFTableRow row : rows) {
List<XWPFTableCell> cells = row.getTableCells();
for (XWPFTableCell cell : cells) {
List<XWPFParagraph> paragraphListTable = cell.getParagraphs();
processParagraphs(paragraphListTable, param, doc);
}
}
}
}
} catch (Exception e) {
e.printStackTrace();
}
return doc;
}
/**
* 處理段落
* @param paragraphList
* @throws Exception
*/
public static void processParagraphs(List<XWPFParagraph> paragraphList,Map<String,
Object> param,CustomXWPFDocument doc) throws Exception{
if(paragraphList != null && paragraphList.size() > 0){
for(XWPFParagraph paragraph:paragraphList){
List<XWPFRun> runs = paragraph.getRuns();
int notFoundCount =0;//最大嘗試計數
for (XWPFRun run : runs) {
//標記是否是標記的開始( 即搜尋到了字元"{" )
Boolean isStart=false;
String text = run.getText(0);
if(text==null){
continue;
}
//遇到左括號開始關注
if(text.contains("{")){
isStart = true;
AddToBasket(run,text,false);
}
//遇到右括號關注結束
if(text.contains("}")){
notFoundCount=0;
AddToBasket(run,text,isStart);
replace(param);
}else if(!text.contains("{")){
notFoundCount++;
int max=50;
if(notFoundCount>max){
throw new Exception("轉換word模板時出錯,超出標記的最大探索次數:"+max);
}
AddToBasket(run,text,false);
}
}
}
}
}
/**
* 放進籃子
*/
private static void AddToBasket(XWPFRun run,String runText,Boolean sameParagraph){
if(!sameParagraph){
tempRuns.add(run);
tempRunTexts.add(runText);
}
}
/**
*
* @param run XWPFRun 段落的片段
* @param runText 段落片段的文字
* @param sameParagraph 是否是同一個段落
* @param param 引數
*/
private static void replace(Map<String,Object> param){
int repaceIndex= 0;
StringBuilder textBuilder =new StringBuilder();
for(int i=0;i<tempRunTexts.size();i++){
String text =tempRunTexts.get(i);
if(!text.contains("}")){
textBuilder.append(text);
//清空開頭的幾個文字
tempRuns.get(i).setText("",0);
}else{
textBuilder.append(text);
}
}
//替換最後一個的文字
String lastText =textBuilder.toString();
boolean isSetText = false;
for (Entry<String, Object> entry : param.entrySet()) {
String key = entry.getKey();
if(lastText.indexOf(key) != -1){
isSetText = true;
Object value = entry.getValue();
if (value instanceof String) {//文字替換
lastText = lastText.replace(key, value.toString());
}
/* else if (value instanceof Map) {//圖片替換
runText = runText.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 =pic.get("content").toString().getBytes();
byte[] byteArray =(byte[]) pic.get("content");
ByteArrayInputStream byteInputStream = new ByteArrayInputStream(byteArray);
try {
@SuppressWarnings("unused")
String ind = doc.addPictureData(byteInputStream,picType);
//System.out.println(doc.getAllPictures().size());
doc.createPicture(doc.getAllPictures().size()-1, width , height,paragraph);
} catch (Exception e) {
e.printStackTrace();
}
} */
}
}
tempRuns.get(tempRuns.size()-1).setText(lastText,0);
//如果還有殘餘標記,則保留最後一個
if(lastText.contains("{")){
for(int i=0;i<tempRunTexts.size();i++){
tempRuns.remove(i);
tempRunTexts.remove(i);
}
}else{
//沒有殘餘標記,則清空
tempRuns.clear();
tempRunTexts.clear();
}
}
/**
* 根據圖片型別,取得對應的圖片型別程式碼
* @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) {
System.out.println("關閉流失敗");
}
}
}
return byteArray;
}
}
9、
package com.test;
import java.io.File;
import java.util.Hashtable;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* @blog http://sjsky.iteye.com
* @author Michael
*/
public class ZxingEncoderHandler {
/**
* 編碼
* @param contents
* @param width
* @param height
* @param imgPath
*/
public static String encode(String contents, int width, int height, String imgPath) {
Hashtable<Object, Object> hints = new Hashtable<Object, Object>();
// 指定糾錯等級
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
// 指定編碼格式
hints.put(EncodeHintType.CHARACTER_SET, "GBK" );
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,
BarcodeFormat.QR_CODE, width, height);
MatrixToImageWriter.writeToFile(bitMatrix, "png" , new File(imgPath));
return "ing";
} catch (Exception e) {
e.printStackTrace();
}
return "zxing";
}
/**
* @param args
*/
public static void main(String[] args) {
String imgPath = "c:/1.png" ;
String contents = "Hello Michael(大大),welcome to Zxing!";
int width = 300 , height = 300 ;
ZxingEncoderHandler handler = new ZxingEncoderHandler();
handler.encode(contents, width, height, imgPath);
System.out.println("Michael ,you have finished zxing encode." );
}
}
四。 word 模板
畢業證書
學校:{學校} 專業:{業績} 編號:${name}
姓名: |
性別:${sex} |
專業: |
${profession} |
頭像: |
${header} ${name} |
二維碼: |
${twocode} |
日期:${date}
二維碼:${twocode}
五.相應的jar包
’