// 以下为两个文件的代码; 可直接下载运行,下载页面:(http://download.csdn.net/detail/lmf462696585/8800097)执行文件是WordUtil4.java。附件的jar包以尽量放进去了,若有运行不了,请自行找寻并下载相关的jar包。若不能下载,请联系邮箱lmf462696585@163.com

// 第一个文件

package com.szpgzx.bas.util;

import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.List;

import org.apache.tools.zip.ZipEntry;
import org.apache.tools.zip.ZipOutputStream;

import com.artofsolving.jodconverter.DocumentConverter;
import com.artofsolving.jodconverter.openoffice.connection.OpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.connection.SocketOpenOfficeConnection;
import com.artofsolving.jodconverter.openoffice.converter.OpenOfficeDocumentConverter;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfWriter;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;

/** 
* doc docx格式转换 
*/  
public class DocConverter {

private static final int environment = 1;// 环境 1:windows 2:linux  
        private String fileString;// (只涉及pdf2swf路径问题)  
   private String outputPath = "";// 输入路径 ,如果不设置就输出在默认的位置  
   private String fileName;  
   private File pdfFile;  
        private File swfFile;  
   private File docFile; 
   
public DocConverter(){}

/**
    * Word转换为PDF
    * @param sourceFile
    * @param destFile
    * @return
    */
   public int office2PDF(String sourceFile, String destFile) {  
       try {  
           File inputFile = new File(sourceFile);  
           if (!inputFile.exists()) {  
               return -1;// 找不到源文件, 则返回-1  
           }  
 
           // 如果目标路径不存在, 则新建该路径  
           File outputFile = new File(destFile);  
           if (!outputFile.getParentFile().exists()) {  
               outputFile.getParentFile().mkdirs();  
           }  
 
           String OpenOffice_HOME = "D:\\Program Files\\OpenOffice.org 3";//这里是OpenOffice的安装目录, 在我的项目中,为了便于拓展接口,没有直接写成这个样子,但是这样是绝对没问题的  
           // 如果从文件中读取的URL地址最后一个字符不是 '\',则添加'\'  
           if (OpenOffice_HOME.charAt(OpenOffice_HOME.length() - 1) != '\\') {  
               OpenOffice_HOME += "\\";  
           }  
           // 启动OpenOffice的服务  
           String command = OpenOffice_HOME  
                   + "program\\soffice.exe -headless -accept=\"socket,host=127.0.0.1,port=8100;urp;\"";  
            Process pro = Runtime.getRuntime().exec(command);  
           // connect to an OpenOffice.org instance running on port 8100  
           OpenOfficeConnection connection = new SocketOpenOfficeConnection(  
                   "127.0.0.1", 8100);  
           connection.connect();  
 
           // convert  
           DocumentConverter converter = new OpenOfficeDocumentConverter(  
                   connection);  
           converter.convert(inputFile, outputFile);  
 
           // close the connection  
           connection.disconnect();  
           // 关闭OpenOffice服务的进程  
           pro.destroy();  
 
           return 0;  
       }catch (Exception e) {  
           e.printStackTrace();  
       }  
       return 1;  
   }  
   
   /**
    * 图片转换为PDF
    * @param imagePath
    * @param mOutputPdfFileName
    * @return
    */
   public File jpg2Pdf(String imagePath, String mOutputPdfFileName) {
       Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
       try {
           PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(
                   mOutputPdfFileName));
           doc.open();
           doc.newPage();
           com.lowagie.text.Image png1 = com.lowagie.text.Image.getInstance(imagePath);
           float heigth = png1.height();
           float width = png1.width();
           int percent = this.getPercent2(heigth, width);
           png1.setAlignment(com.lowagie.text.Image.MIDDLE);
           png1.setAlignment(com.lowagie.text.Image.TEXTWRAP);
           png1.scalePercent(percent + 3);
           doc.add(png1);
           //this.handleText(writer, "This is a test", "red", 400, 725, 0);
           doc.close();
       } catch (FileNotFoundException e) {
           e.printStackTrace();
       } catch (DocumentException e) {
           e.printStackTrace();
       } catch (IOException e) {
           e.printStackTrace();
       }

File mOutputPdfFile = new File(mOutputPdfFileName);
       if (!mOutputPdfFile.exists()) {
           mOutputPdfFile.deleteOnExit();
           return null;
       }
       return mOutputPdfFile;
   }
   private int getPercent2(float h, float w) {
       int p = 0;
       float p2 = 0.0f;
       p2 = 530 / w * 100;
       p = Math.round(p2);
       return p;
    }

public static void main(String s[])
   {
       //DocConverter d=new DocConverter("C:/111.ppt");
    DocConverter d=new DocConverter();
    try {
d.jpg2Pdf("F:\\test\\截图00.JPG", "F:\\test\\截图00.pdf");
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
       //d.conver();
   }

}

//  第二个文件

import java.awt.Image;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.ArrayList;
import java.util.List;

import org.apache.pdfbox.util.PDFMergerUtility;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;

public class WordUtil4 {

// word运行程序对象
    private ActiveXComponent app;
    // 选定的范围或插入点
    private static Dispatch selection;
    private static Dispatch document = null;
    
    public void openWord(boolean makeVisible) {
 //Open Word if we\'ve not done it already
 if (app == null) {
 app = new ActiveXComponent("Word.Application");
 }
 //Set the visible property as required.
 Dispatch.put(app, "Visible", new Variant(makeVisible));
    }
    
    /**
     * 创建Word文档
     *
     */
    public void createNewDocument() {
    //Find the Documents collection object maintained by Word
    Dispatch documents = Dispatch.get(app,"Documents").toDispatch();
    //Call the Add method of the Documents collection to create
    //a new document to edit
    document = Dispatch.call(documents,"Add").toDispatch();
    }
    
    /**
     * 保存Word文档到指定的目录(包括文件名)
     * @param filePath
     */
    public void saveWordFile(final String filePath) {
       //保存文件
          Dispatch.invoke(document, "SaveAs", Dispatch.Method, new Object[] {filePath, new Variant(0)} , new int[1]);
          //作为word格式保存到目标文件
          Variant f = new Variant(false);
          Dispatch.call(document, "Close", f);
    }

/**
* 汇总文件(Word)
* @param fileList
* @param savepaths
*/
public void uniteDoc(List<String> fileList, String savepaths) {
if (fileList.size() == 0 || fileList == null) {
return;
}
//打开word
ActiveXComponent app = new ActiveXComponent("Word.Application");//启动word
try {
// 设置word不可见
app.setProperty("Visible", new Variant(false));
//获得documents对象
Dispatch docs = app.getProperty("Documents").toDispatch();
//打开第一个文件
Dispatch doc = null;
String [] fileStrs = fileList.get(fileList.size()-1).toString().split("\\.");
// 如果是图片,则以图片的方式添加
if (fileStrs[fileStrs.length-1].toUpperCase().equals("JPG") || fileStrs[fileStrs.length-1].toUpperCase().equals("JPEG") 
|| fileStrs[fileStrs.length-1].toUpperCase().equals("PDF") || fileStrs[fileStrs.length-1].toUpperCase().equals("PNG")
|| fileStrs[fileStrs.length-1].toUpperCase().equals("BMP")) {

// 如果是pdf文件,则需要先转换为图片
if(fileStrs[fileStrs.length-1].toUpperCase().equals("PDF")) {
this.pdfjpg(fileList.get(fileList.size()-1).toString(), fileStrs[0]+".jpg");
fileList.set(fileList.size()-1, fileStrs[0]+".jpg");
}

// 创建一个新的Word文档
String wordFile = fileStrs[0]+".doc";
this.createNewWord(wordFile);
// 将新的文档加载到程序中
doc = Dispatch.invoke((Dispatch) docs, "Open", Dispatch.Method, 
new Object[] {wordFile, new Variant(false), new Variant(true)}, new int[3]).toDispatch();
// 加载图片
Dispatch.call(Dispatch.get(app.getProperty("Selection").toDispatch(), "InLineShapes").toDispatch(),"AddPicture", fileList.get(fileList.size()-1));

//document = Dispatch.call(docs,"Add").toDispatch();
//Dispatch.call(Dispatch.get(app.getProperty("Selection").toDispatch(), "InLineShapes").toDispatch(),"AddPicture", fileList.get(i));
}else {
doc = Dispatch.invoke((Dispatch) docs, "Open", Dispatch.Method, 
new Object[] {(String) fileList.get(fileList.size()-1), new Variant(false), new Variant(true)}, new int[3]).toDispatch();
}

// 到文档末尾
//Dispatch.call(app.getProperty("Selection").toDispatch(), "EndKey", "6");
// 插入分页符
//Dispatch.call(app.getProperty("Selection").toDispatch(), "InsertBreak", new Variant(7));

//追加文件
for (int i = 0; i < fileList.size()-1; i++) {
fileStrs = fileList.get(i).toString().split("\\.");

// 如果是图片,则以图片的方式添加
if (fileStrs[fileStrs.length-1].toUpperCase().equals("JPG") || fileStrs[fileStrs.length-1].toUpperCase().equals("JPEG") 
|| fileStrs[fileStrs.length-1].toUpperCase().equals("PDF") || fileStrs[fileStrs.length-1].toUpperCase().equals("PNG")
|| fileStrs[fileStrs.length-1].toUpperCase().equals("BMP")) {
//Dispatch.call(,"AddPicture", fileList.get(i));
// 如果是pdf文件,则需要先转换为图片
if(fileStrs[fileStrs.length-1].toUpperCase().equals("PDF")) {
this.pdfjpg(fileList.get(i).toString(), fileStrs[0]+".jpg");
fileList.set(i, fileStrs[0]+".jpg");
}
// 添加图片
Dispatch.call(Dispatch.get(app.getProperty("Selection").toDispatch(), "InLineShapes").toDispatch(),"AddPicture", fileList.get(i));

}else {

Dispatch.invoke(app.getProperty("Selection").toDispatch(), "insertFile", Dispatch.Method, 
new Object[] {(String) fileList.get(i), "", new Variant(false), new Variant(false), new Variant(false)}, new int[3]);
}

// 到文档末尾
//Dispatch.call(app.getProperty("Selection").toDispatch(), "EndKey", "6");
// 插入分页符
//Dispatch.call(app.getProperty("Selection").toDispatch(), "InsertBreak", new Variant(7));
}
//保存新的word文件
Dispatch.invoke(doc, "SaveAs", Dispatch.Method,
           new Object[] {savepaths, new Variant(1) }, new int[3]);
Variant f = new Variant(false);
Dispatch.call((Dispatch) doc, "Close", f);
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("合并word文件出错.原因:" + e);
} finally {
app.invoke("Quit", new Variant[] {});
}
}

/**
* 汇总文件(PDF)
* @param fileList
* @param savepaths
*/
public void unitePDF(List<String> fileList, String savepaths) throws Exception{
if (fileList.size() == 0 || fileList == null) {
return;
}

PDFMergerUtility mergePdf = new PDFMergerUtility();
DocConverter converter = new DocConverter();

// 添加PDF文件,且只有PDF才可以被汇总
for(int i = 0; i < fileList.size(); i++)
{
String [] pathTemps = fileList.get(i).split("\\\\");
String[] fileTemps = pathTemps[pathTemps.length-1].split("\\.");
String path = "";
for (int p = 0; p < pathTemps.length-1; p++) {
path += pathTemps[p]+"\\";
}
if(fileTemps[fileTemps.length-1].toUpperCase().equals("PDF")) {
mergePdf.addSource(fileList.get(i));
}else if(fileTemps[fileTemps.length-1].toUpperCase().equals("DOC") || fileTemps[fileTemps.length-1].toUpperCase().equals("DOCX")){
// Word转换为PDF
converter.office2PDF(fileList.get(i), path+fileTemps[0]+".PDF");
mergePdf.addSource(path+fileTemps[0]+".PDF");
}else if(fileTemps[fileTemps.length-1].toUpperCase().equals("JPG") || fileTemps[fileTemps.length-1].toUpperCase().equals("JPEG")) {
converter.jpg2Pdf(fileList.get(i), path+fileTemps[0]+".PDF");
mergePdf.addSource(path+fileTemps[0]+".PDF");
}
}
// 汇总生成PDF文件
mergePdf.setDestinationFileName(savepaths);
mergePdf.mergeDocuments();

// 删除那些汇总的文件
for (String filePath : fileList) {
new File(filePath).delete();
}

System.out.print("done");
}

/**
     * pdf文件转换为jpg文件
     * @param pdfFile
     * @param jpgFile
     * @throws IOException
     */
public void pdfjpg(String pdfFile, String jpgFile) throws IOException {

// load a pdf from a byte buffer
File file = new File(pdfFile);
RandomAccessFile raf = new RandomAccessFile(file, "r");
FileChannel channel = raf.getChannel();
ByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel
.size());
PDFFile pdffile = new PDFFile(buf);

System.out.println("页数: " + pdffile.getNumPages());
int with = 0;
int height = 0;
for (int i = 1; i <= pdffile.getNumPages(); i++) {
// draw the first page to an image
PDFPage page = pdffile.getPage(i);
with = (int) page.getBBox().getWidth();
height += (int) page.getBBox().getHeight();
}
Rectangle rect = new Rectangle(0, 0, with,height);
BufferedImage tag = new BufferedImage(rect.width, rect.height,
BufferedImage.TYPE_INT_RGB);
for (int j = 1; j <= pdffile.getNumPages(); j++) {
PDFPage page = pdffile.getPage(j);
Rectangle rect1 = new Rectangle(0, 0, (int) page.getBBox()
.getWidth(), (int) page.getBBox().getHeight());
Image img = page.getImage(rect1.width, rect1.height, // width &
// height
rect1, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);

tag.getGraphics().drawImage(img, 0, rect1.height*(j-1), rect1.width, rect1.height,
null);
}
FileOutputStream out = new FileOutputStream(jpgFile); // 输出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag); // JPEG编码
out.close();

}

/**
* 创建新的文档
* @param filePath
*/
public void createNewWord(String filePath) {
try{
 //Open Word if we\'ve not done it already
 if (app == null) {
 app = new ActiveXComponent("Word.Application");
 }
 //Set the visible property as required.
 Dispatch.put(app, "Visible", new Variant(false));
 
 // 创建新的文档Word
 Dispatch documents = Dispatch.get(app,"Documents").toDispatch();
 document = Dispatch.call(documents,"Add").toDispatch();
     Dispatch.invoke(document, "SaveAs", Dispatch.Method, new Object[] {filePath, new Variant(0)}, new int[1]);
     //作为word格式保存到目标文件
     Variant f = new Variant(false);
     Dispatch.call(document, "Close", f);
     
} catch (Exception e) {
e.printStackTrace();
throw new RuntimeException("合并word文件出错.原因:" + e);
} finally {
app.invoke("Quit", new Variant[] {});
}
}

public static void main(String[] args) {
List list  = new ArrayList();
String file1= "E:\\Word\\ab1.doc";
String file2= "E:\\Word\\ab2.docx";
String file3= "E:\\Word\\ab3.docx";
String file4= "E:\\Word\\ab4.docx";
String file5= "E:\\Word\\ab5.docx";
String file6= "E:\\Word\\ab6.jpg";
String file7= "E:\\Word\\ab7.pdf";

list.add(file1);
list.add(file2);
list.add(file3);
list.add(file4);
list.add(file5);
list.add(file6);
list.add(file7);
new WordUtil4().uniteDoc(list, "E:\\Word\\ab8.docx");

//uniteDoc(list,"E:\\Word\\ab8.docx");
/*Test_Word test = new Test_Word();
test.openWord(true);
test.createNewDocument();
test.saveWordFile("E:\\Word\\new.docx");*/
}
/*public static void main(String[] args) {
Test_Word test = new Test_Word();
System.out.println(test.tidyWord("E:\\Word\\ab.doc", "E:\\Word\\ab.doc"));
}*/
}

使用java将多种类型的文件如Word、PDF、JPG汇总到一个文档中(Word或者PDF)相关推荐

  1. Java在PDF文档中添加或删除页面

    前言 当你编辑一个PDF文档时,有时需要删除文档中多余的页面或向文档中添加新的页面.本文将向您演示如何使用Spire.PDF for Java在PDF文档中添加或删除页面. 程序环境 安装Spire. ...

  2. 多个word文档合并为一个文档 Java实现

    不用额外新建一个空文档,适合需要不断往一个文档中添加其他文档的情况.适合每页格式固定,添加文件新起一页的情况.可进行测试. package could.com.hanwen.govapi.Test;i ...

  3. java读取各类型的文件

    java读取各类型的文件 用到的几个包 bcmail-jdk14-132.jar/bcprov-jdk14-132.jar/checkstyle-all-4.2.jar/FontBox-0.1.0-d ...

  4. JAVA删除pdf空白页_如何编辑PDF文件,如何删除PDF文档中的空白页

    时代在发展,科技在进步,我们现在日常使用的文件也发展了,以前只有Word跟TXT,现在还增加了一个PDF格式的文件,但PDF格式的文件跟Word和TXT文件不一样,Word跟TXT文件可以直接的打开编 ...

  5. java计算机毕业设计网上宠物售卖平台源码+系统+mysql数据库+LW文档+部署文件

    java计算机毕业设计网上宠物售卖平台源码+系统+mysql数据库+LW文档+部署文件 java计算机毕业设计网上宠物售卖平台源码+系统+mysql数据库+LW文档+部署文件 本源码技术栈: 项目架构 ...

  6. java 对word加密_Word文档中怎样给文件信息加密?大神都这样操作,你还不知道?...

    对于Word的使用相信大家都不陌生,在工作中使用Word是很常见的操作,但是很多朋友不知知道一些基础的操作,对于再深奥的点的技能不知道怎样使用,今天小编为大家总结了几个简单的Word操作技巧,希望可以 ...

  7. Java操作word文档将docx转换为pdf格式

    Java操作word文档将docx转换为pdf格式 一.整体说明 在上传 Office 课件时,格式有:doc,docx,xls,xlsx,ppt,pptx,程序需要将其 转换成 pdf 格式, 才能 ...

  8. java读取word文档中的文字和图片,doc和docx兼容版

    也是我东抄抄,西抄抄拿来测试改装的,话不多说,直接上代码 <dependency><groupId>commons-io</groupId><artifact ...

  9. java 绘制pdf_Java 在PDF文档中绘制图形

    本篇文档将介绍通过Java编程在PDF文档中绘制图形的方法.包括绘制矩形.椭圆形.不规则多边形.线条.弧线.曲线.扇形等等.针对方法中提供的思路,也可以自行变换图形设计思路,如菱形.梯形或者组合图形等 ...

最新文章

  1. Coursera台大机器学习技法课程笔记04-Soft-Margin Support Vector Machine
  2. 大白话5分钟带你走进人工智能-第十节梯度下降之归一化的各种方式和必要性(5)...
  3. dedecms5.7 联动类型无法显示
  4. 【JEECG示例文档】使用Kettle从mysql向oracle中抽取数据
  5. CloudFoundry基础知识之理论篇
  6. 5-2计算机视觉的常见概念
  7. Python连接Oracle-常见问题
  8. Android通讯录查询篇--ContactsContract.Data 二
  9. java实现电子面单pdf生成_福利!使用Aspose.Words在Java中将Word格式转换为PDF完整指南...
  10. 【学习笔记:计算几何基础3】 Convex Hull
  11. 数据可视化分析工具评测: DataEase (开源新贵)VS.帆软 FineBI(老牌产品)
  12. 把Matlab的p代码还原为可读的m代码的可能性
  13. 二维非对心弹性碰撞的算法
  14. linux中find查找文件和查找文件内容
  15. 从韩国的大数据之殇,看技术的产业价值与功能价值
  16. 冬夜读书示子聿 鉴赏
  17. Laravel Excel导出xls乱码
  18. 【c++】c++基础入门
  19. VC6使用GdiPlus绘制png图片
  20. 华为设备配置BGP负载分担

热门文章

  1. 三、外码、关系的完整性约束、关系代数
  2. 李宏毅机器学习2020笔记(二)Classification
  3. 飞桨PP-HumanSeg本地实时视频推理代码解读
  4. 博客专家贡献(2022年至今)--2022-11-29(转)
  5. WPS中如何将多个文件在不同窗口中打开
  6. Java类管理机制——包的详解
  7. 我个人的人生学习感想!
  8. 【汇正财经】大盘低开回升
  9. 构建根文件系统(一)
  10. 佳能c3020维修模式 白电平调整_佳能5d3 如何调色温