jacob转换office文件

1.先安装office2010或者wps

2.把jacob-1.18-x86.dll文件放置到本机的java\jdk\jre\bin文件夹之下

3.导入jacob.jar、pdfbox-2.0.9.jar、jai-imageio-core-1.4.0.jar、jai-imageio-jpeg2000-1.3.0.jar包,jacob 使用的是1.18版本的,和jdk 1.6版本号配置,保证程序使用1.6的jdk

4.代码提供word、excel、ppt转换pdf或image,以及pdf转换image的方法,

需要设置临时路径temppath = d:/temp/temp(随便一个路径)

和转换率dpi=150(数字越大清晰度越高图片越大)

上代码:

import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
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.Date;
import java.util.Properties;

import javax.imageio.ImageIO;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.rendering.ImageType;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.apache.poi.POIXMLDocument;
import org.apache.poi.hwpf.extractor.WordExtractor;
import org.apache.poi.openxml4j.opc.OPCPackage;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;

import com.fr.third.org.hsqldb.lib.FileUtil;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class JacobUtil {
	
     // 17代表word保存成pdf
     public static final int WD2PDF = 17;
     public static final int PPT2PDF = 32;
     public static final int XLS2PDF = 0;
     
     private static Properties properties;
     
     private static String getProperties(String key) {
         if (properties == null) {
             properties = new Properties();
             try {
				properties.load(FileUtil.class.getClassLoader().getResourceAsStream("url.properties"));
			} catch (IOException e) {
				e.printStackTrace();
			}
         }
         return properties.get(key) == null ? "" : properties.get(key) + "";
     }
     
     public static void main(String[] agr){
    	 ppt2Image("E:\\1234.pptx", File2byte("E:\\1234.pptx"));
    	 ppt2PDF("E:\\1234.pptx","E:\\4321.pdf");
    	 word2pdf("E:\\12.doc",File2byte("E:\\12.doc"));
 	 }
     
     
 
     public static int getImageFile(byte[] bfile,String name){
 		String extension = name.substring(name.lastIndexOf(".")+1,name.length());
     	if(extension.toLowerCase().matches("doc|docx")){
     		return JacobUtil.word2Image(name,bfile);
     	}
     	if(extension.toLowerCase().matches("xls|xlsx")){
     		return JacobUtil.excel2Image(name,bfile);
     	}
     	if(extension.matches("ppt|pptx")){
     		return JacobUtil.ppt2Image(name,bfile);
     	}
     	if(extension.toLowerCase().matches("pdf")){
     		return JacobUtil.pdf2Image("",bfile);
     	}
     	return 2;
    }
     
 @SuppressWarnings({ "unchecked", "rawtypes" })
public static int pdf2Image(String pdffile,byte[] bfile){
	 
	 if(pdffile!=null&&pdffile!=""&&pdffile.equals("havepsw")){
		 return 0;
	 }
	 
	 if(bfile!=null&&bfile.length>20622976){
		 return 0;
	 }
		 
	 int pageCount = 0;
	 PDDocument doc = null;
	 System.out.println("打开pdf");
	 ByteArrayOutputStream out = new ByteArrayOutputStream();
	 int count = 1;
     try {  
    	 if(pdffile!=""){
    		 doc = PDDocument.load(new File(pdffile));  
    		 System.out.println("*****正在转换...*****"+pdffile);  
    	 }else{
    		 doc = PDDocument.load(bfile);  
    	 }
         PDFRenderer renderer = new PDFRenderer(doc);  
         pageCount = doc.getNumberOfPages(); 
         
         BufferedImage image = null;
         
         for (int i = 0; i < pageCount; ++i) {  
        	 ImageIO.scanForPlugins();
             image = renderer.renderImageWithDPI(i, Float.valueOf(getProperties("dpi")), ImageType.RGB);  
             ImageIO.write(image,"png",out);
             final byte[] bytes = out.toByteArray();
             final int num = i;
             byte2File(bytes,num+".png");
			out.flush();
			out.reset();
			System.out.println("图片转换进度:"+i+"/"+pageCount+"");
         }
     } catch (IOException e) {  
         e.printStackTrace();  
         count = 0;
         System.out.println("pdf转换image出错");
     } finally{  
    	 System.out.println("关闭pdf");
             try {  
            	 doc.close();  
            	 doc = null;
             } catch (IOException e) {  
                 e.printStackTrace();  
             }  
     }

	 return count;
 }
 
 private static BufferedImage merge(BufferedImage image1, BufferedImage image2) {
     BufferedImage combined = new BufferedImage(
    		 image1.getWidth(),
    		 image1.getHeight() + image2.getHeight(),
             BufferedImage.TYPE_INT_RGB);

     Graphics g = combined.getGraphics();
     g.drawImage(image1, 0, 0, null);
     g.drawImage(image2, 0, image1.getHeight(), null);
     g.dispose();
     g = null;
     return combined;
 }
 
 public static int excel2Image(String excelfile,byte[] bfile){
     return pdf2Image(excel2pdf(excelfile,bfile),null);
 }
 
 public static int word2Image(String wordfile,byte[] bfile){
     return pdf2Image(word2pdf(wordfile,bfile),null);
 }
 
 public static int ppt2Image(String pptfile,byte[] bfile){
     return pdf2Image(ppt2pdf(pptfile,bfile),null);
 }
 
 public static String word2pdf(String docfile,byte[] bfile){     
	 String p = docfile.substring(docfile.lastIndexOf("."),docfile.length());
	 
	 if(bfile!=null&&bfile.length>20622976){
		 return "havepsw";
	 }
	 
	 String path = byte2File(bfile,getProperties("temppath")+p);
	 
     boolean flag = false;
     try {
    	 if(p.equals(".doc")){
     	    InputStream is = new FileInputStream(path);
			WordExtractor ex = new WordExtractor(is);
    	 }else if(p.equals(".docx")){
			OPCPackage opcPackage = POIXMLDocument.openPackage(path);
    	 }
     } catch (FileNotFoundException e) {
         e.printStackTrace();
         flag = true;
     } catch (Exception e) {
         e.printStackTrace();
         flag = true;
     } 
     if(flag){
     	return "havepsw";
     }
	 
     ActiveXComponent app = null;  
     String pdf = path.substring(0,path.lastIndexOf("."))+".pdf";
     System.out.println("打开word");  
     try{
    	ComThread.InitSTA(true);
     	app = new ActiveXComponent("Word.Application");     
     	app.setProperty("Visible", false);
     	System.out.println("*****正在转换...*****"+docfile);  
         // 设置word应用程序不可见
         Dispatch docs = app.getProperty("Documents").toDispatch();    
         // 打开要转换的word文件  
         Dispatch doc = Dispatch.call( docs,"Open",path,false,true).toDispatch();     
         
         Dispatch.call(doc, "ExportAsFixedFormat", pdf, WD2PDF);  
         // 关闭word文件  
         Dispatch.call(doc, "Close", false); 
     }     
     catch (Exception e)     
     {   
         e.printStackTrace();  
         System.out.println("word转换image出错");
     }     
     finally    
     {     
    	 System.out.println("关闭应用");
  		 app.invoke("Quit", new Variant[] {});  
         ComThread.Release();
     }
     return pdf;
 }
 
 
 
 public static String ppt2pdf(String pptfile,byte[] bfile){
	 String p = pptfile.substring(pptfile.lastIndexOf("."),pptfile.length());
	String path = byte2File(bfile,getProperties("temppath")+p);
	String pdf = path.substring(0,path.lastIndexOf("."))+".pdf";
 	ActiveXComponent app = null;
 	System.out.println("打开ppt");  
 	try {
 		ComThread.InitSTA(true);
 		app = new ActiveXComponent("PowerPoint.Application");
// 		app.setProperty("Visible", false);
     	System.out.println("*****正在转换...*****"+pptfile);  
 		Dispatch files = app.getProperty("Presentations").toDispatch();
     	Dispatch file = Dispatch.call(files, "Open", path, true, false).toDispatch();
     	Dispatch.call(file, "SaveAs", Dispatch.Method, new Object[]{
       		 pdf,new Variant(PPT2PDF)},new int[1]);
     	Dispatch.call(file,"Close");
		} catch (Exception e) {
			e.printStackTrace();
			System.out.println("ppt转换image出错");
		}finally{
			System.out.println("关闭应用");
	 		app.invoke("Quit", new Variant[] {});  
			ComThread.Release();
		}
 	return pdf;
 }
 
 private static int ppt2PDF(String inputFile, String pdfFile) {
     try {
         ComThread.InitSTA(true);
         ActiveXComponent app = new ActiveXComponent("PowerPoint.Application");
//         app.setProperty("Visible", false);
         System.out.println("开始转化PPT为PDF...");
         long date = new Date().getTime();
         Dispatch ppts = app.getProperty("Presentations").toDispatch();
         Dispatch ppt = Dispatch.call(ppts, "Open", inputFile, true, // ReadOnly
             //    false, // Untitled指定文件是否有标题
                 false// WithWindow指定文件是否可见
         ).toDispatch();
         Dispatch.invoke(ppt, "SaveAs", Dispatch.Method, new Object[]{
                 pdfFile,new Variant(PPT2PDF)},new int[1]);
         System.out.println("PPT");
         Dispatch.call(ppt, "Close");
         long date2 = new Date().getTime();
         int time = (int) ((date2 - date) / 1000);
         app.invoke("Quit");
         return time;
     } catch (Exception e) {
         // TODO: handle exception
         return -1;
     }
 }
 
 public static String excel2pdf(String excelfile,byte[] bfile){
	String p = excelfile.substring(excelfile.lastIndexOf("."),excelfile.length());
	
	if(bfile!=null&&bfile.length>20622976){
		 return "havepsw";
	}
	
	String path = byte2File(bfile,getProperties("temppath")+p);
	
	boolean flag = false;
	Workbook workbook;
	Sheet hssfSheet;
    try {
 	  File file = new File(path);
 	  workbook = WorkbookFactory.create(file);
      hssfSheet = workbook.getSheetAt(0);  //示意访问sheet
    } catch (FileNotFoundException e) {
     e.printStackTrace();
     flag = true;
    } catch (Exception e) {
     e.printStackTrace();
     flag = true;
    } 
    if(flag){
    	return "havepsw";
    }
	
 	ActiveXComponent app = null;
 	String pdf = path.substring(0,path.lastIndexOf("."))+".pdf";
 	System.out.println("打开excel");  
 	try{
 		ComThread.InitSTA(true);
 		app = new ActiveXComponent("Excel.Application");
	    	app.setProperty("Visible", false);
	    	app.setProperty("AutomationSecurity", new Variant(3));//禁用宏
	    	System.out.println("*****正在转换...*****"+excelfile);  
	    	Dispatch excels = app.getProperty("Workbooks").toDispatch();
	    	Dispatch excel = Dispatch.call(excels, "Open", path,false,true).toDispatch();
	    	Dispatch.call(excel, "ExportAsFixedFormat",XLS2PDF, pdf);
	    	Dispatch.call(excel, "Close", false);
 	}catch(Exception e){
 		e.printStackTrace();
 		System.out.println("excel转换image出错");
 	}finally{
 		System.out.println("关闭应用");
 		app.invoke("Quit", new Variant[] {});  
 		ComThread.Release();
 	}
 	return pdf;
 }
 
 public static String byte2File(byte[] bfile, String fileURI) {    
     BufferedOutputStream bos = null;    
     FileOutputStream fos = null;    
     File file = null;  
     File dir = null;  
     try {    
         dir = new File(fileURI.substring(0,fileURI.lastIndexOf("/")+1).replace("/", "\\"));    
         if(!dir.exists()){//判断文件目录是否存在    
             dir.mkdirs();  
         }  
         file = new File(fileURI);  
         fos = new FileOutputStream(file);    
         bos = new BufferedOutputStream(fos);    
         bos.write(bfile);    
     } catch (Exception e) {    
         e.printStackTrace();    
     } finally {    
         if (bos != null) {    
             try {    
                 bos.close();    
             } catch (IOException e1) {    
                 e1.printStackTrace();    
             }    
         }    
         if (fos != null) {    
             try {    
                 fos.close();    
             } catch (IOException e1) {    
                 e1.printStackTrace();    
             }    
         }    
     }    
     return fileURI;
 }  
 
 public static byte[] File2byte(String filePath){
		byte[] buffer = null;
		try
		{
			File file = new File(filePath);
			FileInputStream fis = new FileInputStream(file);
			ByteArrayOutputStream bos = new ByteArrayOutputStream();
			byte[] b = new byte[1024];
			int n;
			while ((n = fis.read(b)) != -1)
			{
				bos.write(b, 0, n);
			}
			fis.close();
			bos.close();
			buffer = bos.toByteArray();
		}
		catch (FileNotFoundException e)
		{
			e.printStackTrace();
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
		return buffer;
	}
 
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值