选择显示字体大小

如何使用jacob将word转换为pdf

如何使用jacob将word转换为pdf

作者cleverpig


版权声明:任何获得matrix授权的网站,转载时请务必以超链接形式标明文章原始出处和作者信息及本声明
作者:cleverpig(http://www.matrix.org.cn/blog/cleverpig)
原文:http://www.matrix.org.cn/resource/article/43/43923_jacob_word_pdf.html
关键字:jacob,word,pdf,com组件

前言:

了解jacob的程序员都知道,jacob是在java与微软的com组件之间的桥梁,通过使用jacob自带的dll动态链接库通过jni的方式实现了在sun java平台上的程序对com调用。jacob的作者照搬了微软java开发包中调用com组件的模式,并将它在sun java平台上实现,可谓是用心良苦啊。
在这里,我们要向jacob的开发者-dan adler致敬,感谢他的开源精神和其团队的伟大贡献!

一、代码实现功能介绍:

  1.写word文件;
  2.调用word文件中的宏;
  3.word文档转换为pdf文件的功能。

二、使用的环境条件:

正是由于jacob的jni这种特性,所以运行jacob的机器上必须要有jacob.dll在系统的path中,而且还要有相应的被调用的com组件存在。

下面列表说明了本项目使用的软件环境和一些注意事项:
  1.word2003、adobe acrobat 7.0.5 professional(由7.0版在线升级获得,因为7.0版存在bug);
  2.并且关闭了adobe pdf打印机属性->adobe pdf setting中的“do not send fonts to pdf”选项;
  3.设置了adobe pdf打印机属性->常规->打印首选项->布局->高级->文档选项->postscript options->truetype font download option为native truetype。
  
第3个条件是可选的,第1、2个条件是必须的。不然会可能出现下面的错误:


三、源代码:

dispatch_msword.java

package com.bjinfotech.practice.jacob;

import com.jacob.com.*;
import com.jacob.activex.*;
/**
* 使用jacob实现以下功能:
*  写word文件;
*  调用word文件中的宏;
*  word文档转换为pdf文件的功能。
*  
*  注意——使用的环境条件:
*  1.word2003、adobe acrobat 7.0.5 professional(由7.0版在线升级获得,因为7.0版存在bug);
*  2.并且关闭了adobe pdf打印机属性->adobe pdf setting中的“do not send fonts to pdf”选项;
*  3.设置了adobe pdf打印机属性->常规->打印首选项->布局->高级->文档选项->postscript options->truetype font download option为native truetype。
*  第3个条件是可选的,第1、2个条件是必须的。不然会可能出现错误。
*  
*  参考资源:
*  create pdf files from microsoft excel using acrobat (6.0 and 7.0 on windows):
*                          http://www.adobe.com/support/techdocs/328398.html
*  article-word doc to pdf conversion
*                          http://www.suodenjoki.dk/us/productions/articles/word2pdf.htm
*  微软的javasdk文档和adobe的distiller api文档(在项目的dependencies目录中)
* @author 聪明的猪
*
*/
public class dispatch_msword {
        private activexcomponent wordcom=null;
        private object worddoc=null;
        private final variant false=new variant(false);
        private final variant true=new variant(true);
        
        /**
         * 打开word文档
         * @param filepath word文档
         * @return 返回word文档对象
         */
        public boolean openword(string filepath){
                //建立activex部件
                wordcom=new activexcomponent("word.application");
                
                try{
                        //返回wrdcom.documents的dispatch
                        object wrddocs=wordcom.getproperty("documents").todispatch();
                        //调用wrdcom.documents.open方法打开指定的word文档,返回worddoc
                        worddoc=dispatch.invoke(wrddocs,"open",dispatch.method,new object[]{filepath},new int[1]).todispatch();
                        return true;
                }
                catch(exception ex){
                        ex.printstacktrace();
                }
                return false;
        }
        
        /**
         * 关闭word文档
         */
        public void closeword(){
                //关闭word文件
                wordcom.invoke("quit",new variant[]{});
        }
        
        /**
         * 打开word,调用word中的宏
         * @param filepath word文件路径
         * @param macroname 被调用的宏名字
         * @param parameter 调用宏的参数数组
         */
        public void callwordmacro(string filepath,string macroname,object parameter[]){

                if (!openword(filepath)){
                        closeword();
                        return;
                }
                else{
                        //使用方法传入的参数parameter调用word文档中的mywordmacro宏
                        dispatch.invoke(worddoc,macroname,dispatch.method,parameter,new int[1]);
                        closeword();
                }
        }
                        
        /**
         * 打开word,替换其中的文字
         * @param filepath word文件路径
         * @param sourcestr 源文字
         * @param replacestr 替换后的文字
         */
        public void callreplaceword(string filepath,string sourcestr,string replacestr){

                if (!openword(filepath)){
                        closeword();
                        return;
                }
                
                try{
                        //获得selection对象
                        dispatch selectdoc=wordcom.getproperty("selection").todispatch();
                        //获得find对象
                        dispatch find = dispatch.call(selectdoc,"find").todispatch();
                        
                        //设置替换的方法属性,但是不支持replacewith的属性,而且使用replancement.text属性也无济于事。
                        dispatch.put(find,"text",sourcestr);
                        
                        //所以使用find对象的execute(findtext, matchcase, matchwholeword, matchwildcards, matchsoundslike, matchallwordforms, forward, wrap, format, replacewith, replace, matchkashida, matchdiacritics, matchalefhamza, matchcontrol)方法
                        //详细内容见msdn的office2000开发文档
                        variant true=new variant(true);
                        variant false=new variant(false);
                        variant findtext=new variant(sourcestr);
                        variant replacewith=new variant(replacestr);
                        variant format=false;
                        variant forward=true;
                        variant matchcase=true;
                        variant matchwholeword=true;
                        variant matchwildcards=false;
                        variant matchsoundslike=false;
                        variant matchallwordforms=false;
                        int wdfindwrap_findcontinue=1;
                        variant wrap=new variant(wdfindwrap_findcontinue);
                        int wdreplace_replaceall=2;
                        variant replace=new variant(wdreplace_replaceall);
                        
                        //使用calln方法调用execute方法
                        dispatch.calln(find,"execute",new variant[]{
                                        findtext, matchcase, matchwholeword, matchwildcards,
                                        matchsoundslike, matchallwordforms, forward, wrap,
                                        format, replacewith, replace
                                });
                        dispatch.invoke(worddoc,"saveas",dispatch.method,new object[]{"c:\\111.doc"},new int[1]);
                        closeword();
                }
                catch(exception ex){
                        ex.printstacktrace();
                }
                finally{
                        closeword();
                }
        }
        
        /**
         * 将word文档打印为ps文件后,使用distiller将ps文件转换为pdf文件
         * @param sourcefilepath 源文件路径
         * @param destinpsfilepath 首先生成的ps文件路径
         * @param destinpdffilepath 生成pdf文件路径
         */
        public void doctopdf(string sourcefilepath,string destinpsfilepath,string destinpdffilepath){
                if (!openword(sourcefilepath)){
                        closeword();
                        return;
                }
                //建立adobe distiller的com对象
                activexcomponent distiller=new activexcomponent("pdfdistiller.pdfdistiller.1");
                try{
                        //设置当前使用的打印机,我的adobe distiller打印机名字为"adobe pdf"
                        wordcom.setproperty("activeprinter",new variant("adobe pdf"));
                        
                        //设置printout的参数,将word文档打印为postscript文档。目前只使用了前5个参数,如果要使用更多的话可以参考msdn的office开发相关api
                        //是否在后台运行
                variant background=false;
                //是否追加打印
                variant append =false;
                //打印所有文档
                int wdprintalldocument=0;
                variant range =new variant(wdprintalldocument);
                //输出的postscript文件的路径
                variant outputfilename =new variant(destinpsfilepath);
//                variant from =new variant(1);
//                variant to  =new variant(1);
//                int wdprintdocumentcontent=2;
//                variant item  =new variant(wdprintdocumentcontent);
//                variant copies =new variant(1);
//                variant pages =new variant();
//                int wdprintallpages=0;
//                variant pagetype =new variant(wdprintallpages);
//                variant printtofile =true;
//                variant collate =true;
//                variant filename =new variant(sourcefilepath);
//                variant activeprintermacgx =new variant();
//                variant manualduplexprint =false;
//                variant printzoomcolumn =new variant();
//                variant printzoomrow  =new variant();
//                variant printzoompaperwidth =new variant();
//                variant printzoompaperheight =new variant();
//        
//                variant[] args=new variant[]{background,append,range,outputfilename,from,to,item,copies,pages,pagetype,
//                                    printtofile,collate,filename,activeprintermacgx,manualduplexprint,printzoomcolumn,printzoomrow,
//                                    printzoompaperwidth,printzoompaperheight};
                
                //调用word文档对象的printout方法:将word文档打印为postscript文档,简称ps文档
                dispatch.calln(worddoc, "printout", new variant[]{background,append,range,outputfilename}) ;
                system.out.println("由word文档打印为ps文档成功!");
                
                //调用distiller对象的filetopdf方法所用的参数,详细内容参考distiller api手册
                //作为输入的ps文档路径
                variant inputpostscriptfilepath=new variant(destinpsfilepath);
                //作为输出的pdf文档的路径
                variant outputpdffilepath=new variant(destinpdffilepath);
                //定义filetopdf方法要使用adobe pdf设置文件的路径,在这里没有赋值表示并不使用pdf配置文件
                variant pdfoption=new variant("");
                //调用filetopdf方法将ps文档转换为pdf文档
                dispatch.calln(distiller,"filetopdf",new variant[]{inputpostscriptfilepath,outputpdffilepath,pdfoption});
                system.out.println("由ps文档转换为pdf文档成功!");
                
                }
                catch(exception ex){
                        ex.printstacktrace();
                }
                finally{
                        closeword();
                }
        }
        
        public static void main(string[] argv){
                dispatch_msword d=new dispatch_msword();
//                d.callwordmacro("e:/eclipse3.1rc3/workspace/jacobpractice/src/com/bjinfotech/practice/jacob/macrotest.doc","mywordmacro",new string[]{"这是调用word宏的测试程序"});
//                d.callreplaceword("e:/eclipse3.1rc3/workspace/jacobpractice/src/com/bjinfotech/practice/jacob/macrotest.doc","$title$","文字已经被替换");
                d.doctopdf("e:/eclipse3.1rc3/workspace/jacobpractice/src/com/bjinfotech/practice/jacob/macrotest.doc","c:/1p.ps","c:/1p.pdf");
        }
}



四、参考资源:
·matrix-java开发者社区:http://www.matrix.org.cn/
·jacob和apache poi相关讨论:http://www.matrix.org.cn/forum.shtml
·create pdf files from microsoft excel using acrobat (6.0 and 7.0 on windows)
·article-word doc to pdf conversion
微软的javasdk文档和adobe的distiller api文档(在项目的dependencies目录中)


五、源代码下载:

源代码中包含了微软java sdk手册和adobe distiller api手册,所以分为5部分供大家下载。
·[下载文件]
·[下载文件]
·[下载文件]
·[下载文件]
·[下载文件]


 


关键字 本文所属关键字

相关 与本文相关文章

分类 所有文章关键字导航

源码编程相关

Java   Asp   PHP   .Net   XML   C/C++   CGI   VB   Jsp   J2ee   J2se   J2me   EJB   Servlet   Tomcat   Resin   Struts   Weblogic   Eclipse   ANT   GUI   JMS   Web servise   IDEA   Webphere   Hibernate   Spring   Jboss   Applet   Swing   Socket   Javamail   Perl   Ajax   P2P   安全   模式   框架   测试   开源   游戏

SQL数据库相关

My-SQL   Ms-SQL   Access   DB2   Oracle   Sybase   SQLserver   索引   存储过程   加密   数据库   分页   视图  

手机无线相关

3G   Wap   CDMA   GRPS   GSM   IVR   彩信   短信   无线   增值业务

网页设计制作相关

HTML   CSS   网页配色   网页特效   Javascript   VBscript   Dreamweaver   Frontpage   JS   Web   网站设计

网站建设推广相关

建站经验   网站优化   网站排名   推广   Alexa

操作系统/服务器相关

Windows XP   Windows 2000   Windows 2003   Windows Me   Windows 9.x   Linux   UNIX   注册表   操作系统   服务器   应用服务器

图形图像多媒体相关

Photoshop   Fireworks   Flash   Coreldraw   Illustrator   Freehand   Photoimpact   多媒体   图形图像

标准 网站致力的规范

Valid CSS!

无不良内容,无不良广告,无恶意代码

Valid XHTML 1.0 Transitional

creativecommons