`

word转pdf

    博客分类:
  • java
阅读更多
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.util.HashSet;
import java.util.Set;

import org.apache.log4j.Logger;

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.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;

public class FileConverterService {
private static final Logger logger = Logger.getLogger(FileConverterService.class);
private static final Set<String> OFFICE_TYPE = new HashSet<String>();
private static final String VISIO_TYPE = "vsd";
private static String webPath = "";
    private static String webFileName = "";
   
static{
OFFICE_TYPE.add("doc");
OFFICE_TYPE.add("docx");
OFFICE_TYPE.add("xls");
OFFICE_TYPE.add("xlsx");
OFFICE_TYPE.add("ppt");
OFFICE_TYPE.add("pptx");
OFFICE_TYPE.add("txt");
}

public static boolean canReadOnLine(String filePath){
boolean flag = false;
int index = filePath.lastIndexOf(".");
String extName = filePath.substring(index + 1);
flag = isPdfFile(extName) || isOfficeFile(extName) || isVisioFile(extName);
return flag;
}

public static boolean convertFile2Swf(String fileFullName){
boolean flag = false;
if(null != fileFullName){
String tmpFileName = null;
int index = fileFullName.lastIndexOf(".");
String fileName = fileFullName.substring(0,index);
String extName = fileFullName.substring(index + 1);
if(isOfficeFile(extName)){
tmpFileName = fileName + ".pdf";
boolean opFlag = convertOffice2Pdf(fileFullName, tmpFileName, fileFullName.substring(index + 1, fileFullName.length()));
if(opFlag){
try{
flag = convertPdf2Swf(tmpFileName, fileName+".swf");
}catch(Exception e){
logger.error("将Office文档的PDF文档转换成SWF文件失败!", e);
}
}
}else if(isPdfFile(extName)){
flag = convertPdf2Swf(fileFullName, fileName+".swf");
}else if(isVisioFile(extName)){
tmpFileName = fileName + ".pdf";
boolean opFlag = convertVisio2Pdf(fileFullName);
if(opFlag){
try{
flag = convertPdf2Swf(tmpFileName, fileName+".swf");
}catch(Exception e){
logger.error("将VISIO创建的PDF文档转换成SWF文件失败!", e);
}
}
}
}
return flag;
}

/**
* 将Office文档转换成PDF文档(新)。
* @param inFileName
* @param outFileName
*/
private static boolean convertOffice2Pdf(String inFileName, String outFileName,String extName){
     boolean flag = false;
     if("doc".equals(extName.toLowerCase()) || "docx".equals(extName.toLowerCase())){
         flag = FileWordToPdf.wordToPDF(inFileName, outFileName, 17);
     }
     else{
         return convertOffice2Pdf(inFileName,outFileName);
     }
     return flag;
}

/**
* 将Office文档转换成PDF文档。
* @param inFileName
* @param outFileName
*/
private static boolean convertOffice2Pdf(String inFileName, String outFileName){
boolean flag = false;
OpenOfficeConnection connection = null;
try{
File inFile = new File(inFileName);
File outFile = new File(outFileName);
connection = new SocketOpenOfficeConnection(8100);
connection.connect();
DocumentConverter converter = new OpenOfficeDocumentConverter(connection);
converter.convert(inFile, outFile);
flag = true;
}catch(Exception e){
logger.error("将Office文档转换为PDF文档失败!", e);
}finally{
if(null != connection){
connection.disconnect();
}
}
return flag;
}

/**
* 将VISIO文档转换成PDF文档。
* 分为两步:
* 1、将VSD各页转换成emf图片文件
* 2、将所有的emf转换成PDF
* @param inFileName
* @param outFileName
*/
private static boolean convertVisio2Pdf(String inFileName){
boolean flag = false;
try{
ComThread.InitSTA();
java.util.ArrayList<String> tmpFileName = null;
int index = inFileName.lastIndexOf(".");
String tmpDescPath = inFileName.substring(0,index);
ActiveXComponent vsd = null;
StringBuffer command = null;
vsd = new ActiveXComponent("Visio.Application");
vsd.setProperty("Visible", new Variant(false));
Dispatch docs = vsd.getProperty("Documents").toDispatch();
Dispatch doc = Dispatch.call(docs, "Open", inFileName).toDispatch();
Dispatch pages = Dispatch.get(doc, "Pages").toDispatch();
if(null != pages){
tmpFileName = new java.util.ArrayList<String>();
command = new StringBuffer("im_convert ");
int count = Integer.parseInt(Dispatch.get(pages, "Count").toString());
for(int i = 1; i <= count; i++){
Dispatch page = Dispatch.call(pages, "item", new Object[]{ new Integer(i)}).toDispatch();
String name = Dispatch.get(page, "Name").toString();
String emfName = tmpDescPath + "_" + name + ".emf";
tmpFileName.add(emfName);
Dispatch.call(page, "Export", new Object[]{emfName });
command.append(emfName + " ");
}
}
Dispatch.put(doc, "Saved", new Variant(true));
vsd.invoke("Quit", new Variant[]{});
command.append(tmpDescPath+".pdf");
Process pro = Runtime.getRuntime().exec(command.toString());
StreamGobbler errGob = new StreamGobbler(pro.getErrorStream(),"ERROR");
StreamGobbler outGob = new StreamGobbler(pro.getInputStream(),"OUTINFO");
errGob.start();
outGob.start();
if(0 == pro.waitFor()){
flag = true;
}
// 删除临时的图片文件
File file = null;
if(null != tmpFileName){
for(String name: tmpFileName){
file = new File(name);
if(null != file && file.exists()){
file.delete();
}
}
}
}catch(Exception e){
logger.error("将VISIO文档转换为PDF文档失败!", e);
}finally{
ComThread.Release();
}
return flag;
}

/**
* 将PDF转换为SWF文档。
* @param inFileName
* @param outFileName
*/
private static boolean convertPdf2Swf(String inFileName, String outFileName){
boolean flag = false;
try{
    if(hasFileDir(outFileName)){
StringBuffer command =
new StringBuffer("pdf2swf -G -f -T 9 -t -s storeallcharacters ").append(inFileName).append(" -o ").append(webPath + webFileName);
// 执行命令是在单独的线程中完成。不等完成就直接返回。
Process pro = Runtime.getRuntime().exec(command.toString());
StreamGobbler errGob = new StreamGobbler(pro.getErrorStream(),"ERROR");
StreamGobbler outGob = new StreamGobbler(pro.getInputStream(),"OUTINFO");
errGob.start();
outGob.start();
if(0 == pro.waitFor()){
flag = true;
// if(hasFileDir(outFileName)){
//        System.out.println("-------webPath:"+webPath + webFileName);
//        String str = "copy "+ outFileName + " "+webPath + webFileName;
//        System.out.println("-------str:"+str);
//               //forChannel(outFileName,webPath + webFileName);
//       pro = Runtime.getRuntime().exec(str);
//           }
}
    }
}catch(Exception e){
logger.error("将PDF文档转换为SWF文档失败或者拷贝文件失败!", e);
}
return flag;
}

/**
* 根据文件判断是否为Office文档,doc、docx、xls、xlsx、ppt、pptx
* @param fileName
* @return
*/
private static boolean isOfficeFile(String extName){
if(null != extName){
if(OFFICE_TYPE.contains(extName.toLowerCase())){
return true;
}
}
return false;
}

/**
* 根据文件扩展名判断是否为PDF文件。
* @param fileName
* @return
*/
private static boolean isPdfFile(String extName){
if("pdf".equalsIgnoreCase(extName)){
return true;
}
return false;
}

/**
* 根据文件扩展名判断是否为VISIO文件。
* @param fileName
* @return
*/
private static boolean isVisioFile(String extName){
if(VISIO_TYPE.equalsIgnoreCase(extName)){
return true;
}
return false;
}

public static boolean hasFileDir(String fileFullName){
        boolean flag = false;
        if(fileFullName == null || "".equals(fileFullName)){
            return flag;
        }
        int totalen = fileFullName.length();
        int len = fileFullName.lastIndexOf("\\");
        String cfile = fileFullName.substring(0,len);
        webFileName = fileFullName.substring(len+1);
        int tlen = cfile.lastIndexOf("\\");
        String filedirName = fileFullName.substring(tlen+1, len);
//        String urls = ClassLoader.getSystemResource("\\").getPath();
//        int wlen = urls.indexOf("WEB-INF");
//        String absolutePath = urls.substring(1,wlen);
         String userdir = System.getProperty("user.dir");
         String tomPath = userdir.replace("bin", "");
        String absolutePath = tomPath+"webapps\\smis\\tempdocument\\attachment\\";
        //String absolutePath = "D:\\work\\smis\\WebRoot\\tempdocument\\attachment\\";
        webPath = absolutePath + filedirName + "\\";
//        System.out.println("-----------:"+webPath);
        File file = new File(webPath);
        if(file.exists()){
            flag = true;
        }
        else{
            file.mkdirs();
            flag = true;
        }
        return flag;
    }
   
    public static boolean forChannel(String s1,String s2) throws Exception{
        boolean flag = false;
        int length=2097152;
        File f1 = new File(s1);
        File f2 = new File(s2);
        FileInputStream in=new FileInputStream(f1);
        FileOutputStream out=new FileOutputStream(f2);
        FileChannel inC=in.getChannel();
        FileChannel outC=out.getChannel();
        ByteBuffer b=null;
        while(true){
            if(inC.position()==inC.size()){
                inC.close();
                outC.close();
                flag = true;
            }
            b=ByteBuffer.allocateDirect(length);
            b.flip();
            outC.write(b);
            outC.force(false);
            outC.close();
        }
       
    }
}

写个线程类StreamGobbler

/**
* aaron_ye
*/
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.PrintWriter;

/**
* @author aaron_ye
*
*/
public class StreamGobbler extends Thread {

private InputStream is = null;
private OutputStream os = null;
private String type = null;

public StreamGobbler(InputStream _is, String _type, OutputStream _os){
this.is = _is;
this.os = _os;
this.type = _type;
}

public StreamGobbler(InputStream _is, String _type){
this.is = _is;
this.type = _type;
}

public void run() {
try{
// System.out.println("begin: "+this.type);
PrintWriter pw = null;
if (os != null){
pw = new PrintWriter(os);
}else{
pw = new PrintWriter(System.out);
}
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String line=null;
while ( (line = br.readLine()) != null){
if (pw != null){
pw.println(line);
}
}
if (pw != null){
pw.flush();
}
// System.out.println("end: "+this.type);
} catch (IOException ioe){
ioe.printStackTrace();
}
}



/**
* @return the is
*/
public InputStream getIs() {
return is;
}

/**
* @param is
*            the is to set
*/
public void setIs(InputStream is) {
this.is = is;
}

/**
* @return the os
*/
public OutputStream getOs() {
return os;
}

/**
* @param os
*            the os to set
*/
public void setOs(OutputStream os) {
this.os = os;
}

/**
* @return the type
*/
public String getType() {
return type;
}

/**
* @param type
*            the type to set
*/
public void setType(String type) {
this.type = type;
}


}

分享到:
评论

相关推荐

    word 转PDF的几种方式

    word 转PDF的几种方式 1、NPOI读取Word,只支持后缀名为.docx的,用iTextSharp生成pdf文件,存在读取word的段落,表格及先后顺序,导致生成的也不一致。 2、通过读取字节判断。 3、通过Aspose.Words来操作,在项目...

    java实现word转pdf

    java实现word转pdf 效果及使用教程可以参考 https://blog.csdn.net/u012775558/article/details/121530527

    利用poi+itextpdf进行word转pdf.rar

    java 利用利用poi+itextpdf进行word转pdf,里面有源码和依赖还有效果图,无需安装插件,感觉是一种比较好的方法

    最好用的word转pdf工具

    专业版的pdf软件,也就是700多兆大小的那个软件,具有转pdf的功能,但是,本人在使用过程中发现,通过visio画图工具所画的图形和汉字,在插入到word后,然后将word转pdf中,转换时常常不能将文字正常显示。...

    Word转PDF文件,如何在PDF中嵌入字体[收集].pdf

    Word 转 PDF 文件中的字体嵌入方法 在软件开发中,经常需要将 Word 文档转换为 PDF 文件,并在 PDF 文件中嵌入字体,以满足某些杂志的上传要求,例如 ASCE 杂志。下面将详细介绍如何在 PDF 文件中嵌入字体。 首先...

    libreoffice实现word转pdf

    使用Libreoffice 完美实现在线word转pdf.支持word和linux两个系统

    实现Word转PDF(基于SWT)

    网络上有很多种Word转PDF的方式(openoffice,jacob,POI),但都不是很完美,要不依赖三防包还要下载dll文件,要不转换不完美,还不支持中文,我的转换方式使用eclipse自带的swt包即可,程序引用swt的jar后直接运行

    利用poi+itextpdf进行word转pdf.zip

    将word转换成pdf确实有很多种方案!最近正好需要做一个这样的功能,需求是将word模板进行签名后转换为pdf。...这里记录一下最终的方案:利用poi+itextpdf进行word转pdf。此资源按包含源码和maven依赖。

    word转pdf工具

    word转pdf工具word转pdf工具word转pdf工具word转pdf工具word转pdf工具

    aspose实现word转pdf功能(去水印)

    java实现word转pdf功能,并实现去水印,本人测试真实有效。 操作简单,傻瓜式教程!!! 提供mvn安装本地依赖命令。

    Word转PDF带有导航页或书签详细教程

    大家在编辑Word的时候,会设置大纲目录,在看内容时通过导航页即可快速转到相应位置,但是转成pdf格式时,这个导航页就没了,本文旨在介绍Word转PDF带有导航页或书签详细步骤。转成pdf的方法,这里主要介绍两种,...

    word转PDF然后实现在线预览的功能.rar

    自己项目中用到的技术,word转PDF然后实现在线预览的功能,代码可以运行 .

    word转pdf所需的jar包

    纯Java代码实现word转pdf,所需要用到的jar包。 https://juejin.cn/post/7087036463035973640/

    Aspose.Words Java实现word转pdf文件(高效不失真)

    Aspose.Words Java实现word转pdf文件(高效不失真)。提供license文件。提供源代码。提供jar。下载即可直接使用。Word2PdfUtil.java、license.xml、Aspose.Words-jdk16.jar

    XML Worker Word转PDF/html工具类

    代码用maven方式引入jar包 无嵌入式处理word文件,工具类包括 1. docx转html处理 ...3. word转pdf处理 Word2Pdf.java (poi itext7) 4. word模板填充 WordUtils.java (poi XWPF) 5. 序列id生成 6. 文件处理通用工具类

    word转pdf---虚拟打印

    word转pdf word转pdfword转pdfword转pdfword转pdfword转pdf

    word转pdf jar下载

    word转pdf jar下载,word转pdf jar下载,word转pdf jar下载word转pdf jar下载

    云夹免费word转pdf工具转换器 v2.21.zip

    云夹word转pdf工具(pdf转换成word转换器)是一款功能强大好用的word转pdf且pdf转换成word软件工具,df转换成word工具是一款Word文档格式转换成Pdf文档格式工具,是PDF与Word相互转换工具,用户可以很容易的得到转换...

    Word转PDF-java

    java用的Word转PDF工具jar包,

Global site tag (gtag.js) - Google Analytics