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 = ""    
                + ""   
                + "   "   
                + "      "   
                + "         " + "                            + id    
                + "\" name=\"Generated\"/>"    
                + "            "    
                + "        
"    
                + "         "    
                + "                            + blipId    
                + "\" xmlns:r=\"http://schemas.openxmlformats.org/officeDocument/2006/relationships\"/>"   
                + "            "    
                + "               "    
                + "           
"    
                + "        
"    
                + "         "    
                + "            "    
                + "               "    
                + "                               + width    
                + "\" cy=\""    
                + height    
                + "\"/>"    
                + "           
"    
                + "            "    
                + "               "    
                + "           
"    
                + "        
"    
                + "     
"    
                + "  
" + "
";    
    
        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 {
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 param = new HashMap();  
    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 li, final Map map) throws Throwable, Throwable{
     System.out.println("----程序开始运行----");
       Date date1 = new Date();

       int taskSize = 1;
       // 创建一个线程池
       ExecutorService pool = Executors.newFixedThreadPool(taskSize);
       
       //创建缓存线程池,根据任务来自动创建线程的数量,可以完成创建的所有任务  
      // ExecutorService threadPool = Executors.newCachedThreadPool();  
       
       
       // 创建多个有返回值的任务
       List list = new ArrayList();
       
       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 param = new HashMap();  
                    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                           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 list = new ArrayList(){{add("c://oop.docx"); add("c://oop1.docx");}};
        Map map =new HashMap();
        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 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 getReplaceElementsInWord(String filePath,
            String regex) {
        String[] p = filePath.split("\\.");
        if (p.length > 0) {// 判断文件有无扩展名
            // 比较文件扩展名
            if (p[p.length - 1].equalsIgnoreCase("doc")) {
                ArrayList 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 al = new ArrayList<>();
                XWPFDocument document = null;
                try {
                    document = new XWPFDocument(
                            POIXMLDocument.openPackage(filePath));
                } catch (IOException e) {
                    e.printStackTrace();
                }
                // 遍历段落
                Iterator 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 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 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 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 itPara = document
                            .getParagraphsIterator();
                    while (itPara.hasNext()) {
                        XWPFParagraph paragraph = (XWPFParagraph) itPara.next();
                        List runs = paragraph.getRuns();
                        for (int i = 0; i < runs.size(); i++) {
                            String oneparaString = runs.get(i).getText(
                                    runs.get(i).getTextPosition());
                            for (Map.Entry entry : map
                                    .entrySet()) {
                                oneparaString = oneparaString.replace(
                                        entry.getKey(), entry.getValue());
                            }
                            runs.get(i).setText(oneparaString, 0);
                        }
                    }

                    // 替换表格中的指定文字
                    Iterator 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 cells = row.getTableCells();
                            for (XWPFTableCell cell : cells) {
                                String cellTextString = cell.getText();
                                for (Entry 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 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 map = new HashMap();
        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 tempRuns =new ArrayList();
    
    
    /** 临时存放要替换的元素的文本
     */
    private static List tempRunTexts =new ArrayList();
    
    /**
     * 封装的工具类WordUtil.java
     * 根据指定的参数值、模板,生成 word 文档
     * @param param 需要替换的变量
     * @param template 模板
     */  
    public static CustomXWPFDocument generateWord(Map param, String

template) {  
        CustomXWPFDocument doc = null;  
        try {  
            OPCPackage pack = POIXMLDocument.openPackage(template);  
            doc = new CustomXWPFDocument(pack);  
            if (param != null && param.size() > 0) {  
                  
                //处理段落  
                List paragraphList = doc.getParagraphs();  
                processParagraphs(paragraphList, param, doc);  
                  
                //处理表格  
                Iterator it = doc.getTablesIterator();  
                while (it.hasNext()) {  
                    XWPFTable table = it.next();  
                    List rows = table.getRows();  
        
        for (XWPFTableRow row : rows) {  
                        List cells = row.getTableCells();  
                        for (XWPFTableCell cell : cells) {  
                            List paragraphListTable =  cell.getParagraphs();
                            processParagraphs(paragraphListTable, param, doc);  
                        }  
                    }  
                }  
            }  
        } catch (Exception e) {  
            e.printStackTrace();  
        }  
        return doc;  
    }  
    
    /**
     * 处理段落
     * @param paragraphList
     * @throws Exception
     */  
    public static void processParagraphs(List paragraphList,Map Object> param,CustomXWPFDocument doc) throws Exception{  
        if(paragraphList != null && paragraphList.size() > 0){  
            for(XWPFParagraph paragraph:paragraphList){  
                List 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 param){
        int repaceIndex= 0;
        StringBuilder textBuilder =new StringBuilder();
        for(int i=0;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 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                 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 hints = new  Hashtable();  
        // 指定纠错等级   
        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包

java 编码填充 word 模板生成 word合同,并将word合同转成pdf 文档_第1张图片




        




你可能感兴趣的:(java 编码填充 word 模板生成 word合同,并将word合同转成pdf 文档)