JAVA------10.复制word,更改word内容,将word转pdf (在windows环境下)

jar包 和相关类

1、CopyFileUtil 拷贝文件

 1 package com.caipei.util;
 2 
 3 import java.io.File;
 4 import java.io.FileInputStream;
 5 import java.io.FileOutputStream;
 6 import java.io.IOException;
 7 import java.nio.channels.FileChannel;
 8 
 9 import org.apache.poi.xwpf.usermodel.XWPFDocument;
10 import org.apache.poi.xwpf.usermodel.XWPFParagraph;
11 import org.apache.poi.xwpf.usermodel.XWPFRun;
12 
13 
14 /**
15  * 文件拷贝目录
16  * @author Administrator
17  *
18  */
19 public class CopyFileUtil {
20 
21     /**
22      * 将源文件拷贝一份
23      * @param source
24      * @param target
25      */
26     public static void nioTransferCopy(File source, File target) {  
27         FileChannel in = null;  
28         FileChannel out = null;  
29         FileInputStream inStream = null;  
30         FileOutputStream outStream = null;  
31         try {  
32             inStream = new FileInputStream(source);  
33             outStream = new FileOutputStream(target);  
34             in = inStream.getChannel();  
35             out = outStream.getChannel();  
36             in.transferTo(0, in.size(), out);  
37         } catch (IOException e) {  
38             e.printStackTrace();  
39         }  
40     }  
41     
42     /***
43      * 创建一个新文件
44      * @return
45      */
46     public static String writeDoc() {
47         XWPFDocument doc = new XWPFDocument(); 
48         XWPFParagraph p1 = doc.createParagraph();
49         XWPFRun r1 = p1.createRun();
50         r1.setText("hello world");
51         String a="D:/html转pdf/总结/Test/Test20170328哈.doc";
52         try {
53             FileOutputStream out = new FileOutputStream(a);
54             doc.write(out);  
55             out.close();
56         } catch (Exception e) {
57             // TODO: handle exception
58             e.printStackTrace();
59         }
60         return a; 
61     }
62     
63     public static void main(String[] args) {
64          File srcFile = new File("D:/html转pdf/总结/Test/1.doc");  
65             File desfFile = new File("D:/html转pdf/总结/Test/3.doc");
66         nioTransferCopy(srcFile,desfFile);
67     }
68 }

FileInToUtil 在文档中根据键值 插入数据

 1 package com.caipei.util;
 2 
 3 import java.io.ByteArrayOutputStream;
 4 import java.io.File;
 5 import java.io.FileInputStream;
 6 import java.io.FileOutputStream;
 7 import java.io.IOException;
 8 import java.util.Map;
 9 
10 import org.apache.poi.hwpf.HWPFDocument;
11 import org.apache.poi.hwpf.usermodel.Range;
12 
13 /**
14  * 在文档中根据键值 插入数据
15  * @author Administrator
16  *
17  */
18 public class FileInToUtil {
19     public static void writeDoc(String path,Map<String, String> map) {  
20         try {  
21             FileInputStream in = new FileInputStream(path);  
22             HWPFDocument hdt = new HWPFDocument(in);  
23             Range range = hdt.getRange();  
24             //读取word文本内容  
25             System.out.println(range.text());  
26             //替换文本内容  
27             for (Map.Entry<String,String> entry:map.entrySet()) {  
28                 range.replaceText(entry.getKey(),entry.getValue());  
29             }  
30 
31             ByteArrayOutputStream ostream = new ByteArrayOutputStream();  
32             FileOutputStream out = new FileOutputStream(path);  
33             hdt.write(ostream);  
34             //输出字节流  
35             out.write(ostream.toByteArray());  
36             ostream.close();  
37         } catch (IOException e) {  
38             e.printStackTrace();  
39         } catch (Exception e) {  
40             e.printStackTrace();  
41         }  
42     }
43 }

 WordToPDF OpenOffice的安装目录

 1 package com.caipei.util;
 2 
 3 import java.io.File;
 4 import com.artofsolving.jodconverter.DocumentConverter;
 5 import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
 6 import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
 7 import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
 8 
 9 
10 
11 /**
12  * OpenOffice的安装目录
13  * @author Administrator
14  *
15  */
16 public class WordToPDF {
17     
18      
19     public void docToPdf(File inputFile, File outputFile){
20         //启动服务
21         String OpenOffice_HOME = "C:/Program Files (x86)/OpenOffice 4";// 这里是OpenOffice的安装目录
22         if(OpenOffice_HOME.charAt(OpenOffice_HOME.length()-1)!='/'){
23             OpenOffice_HOME+="/";
24         }
25         Process pro = null;
26         OpenOfficeConnection connection = null;
27          // 启动OpenOffice的服务   
28         String command = OpenOffice_HOME + "program/soffice.exe -headless -accept="socket,host=localhost,port=8100;urp;"";
29          // connect to an OpenOffice.org instance running on port 8100
30        
31         try{
32             pro = Runtime.getRuntime().exec(command);
33             connection = new SocketOpenOfficeConnection(8100);
34             connection.connect();
35             
36              // convert
37             DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
38             System.out.println(inputFile+"="+outputFile);
39             
40             converter.convert(inputFile, outputFile);
41         }catch(Exception ex){
42             System.out.println("程序出错了");
43             ex.printStackTrace();
44             
45         }finally{
46             // close the connection
47             if(connection!=null){
48                 connection.disconnect();
49                 connection = null;
50             }
51             pro.destroy();
52         }
53            System.out.println("生成"+outputFile.getName());
54     }
55     
56     //生产pdf线程
57     static class TestThread extends java.lang.Thread{
58         private File inputFile;
59         private File outputFile;
60         
61         public void run(){
62             WordToPDF t = new WordToPDF();
63             t.docToPdf(inputFile, outputFile);
64             System.out.println(outputFile.getName()+"文件已生成");
65         }
66 
67         public void setInputFile(File inputFile) {
68             this.inputFile = inputFile;
69         }
70 
71         public void setOutputFile(File outputFile) {
72             this.outputFile = outputFile;
73         }
74         
75         
76     }
77     
78     
79     
80 
81 }

Word2PDFUtil  word 转pdf

 1 package com.caipei.util;
 2 
 3 import java.io.File;
 4 import java.io.FilenameFilter;
 5 
 6 import com.caipei.util.WordToPDF.TestThread;
 7 
 8 /*
 9  * word 转pdf
10  */
11 public class Word2PDFUtil {
12     
13     /**
14      * @param dirs doc转换文件夹,批量转换
15      */
16     /*public static void word2Pdf(File file,String path){
17          File dir = new File(dirs); 
18          File[] files = dir.listFiles(new WordFilenameFilter()); 
19            //遍历文件夹方式
20             if (files == null||files.length==0){
21                 throw new NullPointerException("该路径下没有doc文件");
22             }
23             for (int i = 0; i < files.length; i++) { 
24                     String strFileName = files[i].getAbsolutePath().toLowerCase(); 
25                     TestThread t1 = new WordToPDF.TestThread();
26                     //输入文件名
27                    t1.setInputFile(new File(strFileName));
28                     //获得"."前面的文件名并将其输入为PDF
29                     t1.setOutputFile(new File(strFileName.substring(0,strFileName.indexOf("."))+".pdf"));
30                     t1.start();
31             }
32     
33     } */
34     
35     
36     public static void wordPdf(String srccpath,String topath){
37          File file = new File(srccpath); 
38            //遍历文件夹方式
39                     String strFileName = file.getAbsolutePath().toLowerCase(); 
40                     TestThread t1 = new WordToPDF.TestThread();
41                     //输入文件名
42                    t1.setInputFile(new File(topath));
43                     //获得"."前面的文件名并将其输入为PDF
44                     t1.setOutputFile(new File(strFileName.substring(0,strFileName.indexOf("."))+".pdf"));
45                     t1.start();
46    } 
47 
48     /**
49      * @param orgfileName 原始word文件名
50      * @param descFileName 生成pdf文件名
51      */
52     public static void word2Pdf(String orgfileName, String descFileName) {
53         if(!isWord(orgfileName)||descFileName==null){
54             throw new IllegalArgumentException("原始word文件名不是word文档,或者descFileName为空");
55         }
56         TestThread t1 = new WordToPDF.TestThread();
57         // 输入文件名
58         t1.setInputFile(new File(orgfileName));
59         // 获得"."前面的文件名并将其输入为PDF
60         t1.setOutputFile(new File(descFileName.substring(0, descFileName
61                 .indexOf("."))
62                 + ".pdf"));
63         t1.start();
64     }
65     static class WordFilenameFilter implements FilenameFilter{
66         @Override
67         //只转换word文档
68         public boolean accept(File dir, String name) {
69             return isWord(name);
70         }
71         
72     }
73     /**
74      * @param name 文件名
75      * @return 判断是否为doc word文档
76      */
77     private static boolean isWord(String name){
78         return name.endsWith(".doc")||name.endsWith(".docx")||name.endsWith(".wps");
79         //return true;
80     }
81 }

Test 

//1、先找到源word文件
//2、复制word文件 并重新命名word
//3、修改 新命名的word文件内容
//4、将word 转化成 pdf 文件 并保存

 1 package com.shunan;
 2 
 3 import java.io.File;
 4 import java.util.Date;
 5 import java.util.HashMap;
 6 import java.util.Map;
 7 
 8 import com.caipei.util.CopyFileUtil;
 9 import com.caipei.util.FileInToUtil;
10 import com.caipei.util.Word2PDFUtil;
11 
12 
13 
14 public class Test {
15 
16     /**
17      * @param args
18      */
19     public static void main(String[] args) {
20         // TODO Auto-generated method stub
21         
22         //1、先找到源word文件 
23         //2、复制word文件 并重新命名word
24         //3、修改 新命名的word文件内容
25         //4、将word 转化成 pdf 文件 并保存
26         
27         //源文件
28         File srcFile = new File("D:/html转pdf/总结/Test/baseFile/baseFile.doc");
29          Date date=new Date();
30          String time=String.valueOf(date.getTime());
31          String newpath="D:/html转pdf/总结/Test/"+time+".doc";
32         File desfFile = new File(newpath);
33         
34         String fileName=desfFile.getName();
35         
36         System.out.println(fileName);
37         
38         CopyFileUtil.nioTransferCopy(srcFile,desfFile);
39         
40         //遍历集合
41         Map<String, String> map = new HashMap<String, String>();
42         map.put("name", "蔡培");
43         
44         //将文件内 键值更改
45         FileInToUtil.writeDoc(newpath, map);
46         
47         String strFileName = desfFile.getAbsolutePath().toLowerCase();
48         
49         //将word转换成 pdf
50         Word2PDFUtil.wordPdf(strFileName,strFileName);
51         
52          
53     }
54 
55 }

 lib 和测试路径

链接:http://pan.baidu.com/s/1c2KNMCg 密码:9ve5

Apache_OpenOffice_4.1.2_Win_x86_install_zh-CN.exe

链接:http://pan.baidu.com/s/1eRRVb2M 密码:wdp5

 源码:

链接:http://pan.baidu.com/s/1bQHotw 密码:tzzc

注意: 1、OpenOffice的安装目录一定要修改,程序在开启状态
原文地址:https://www.cnblogs.com/coriander/p/6635416.html