packagecom.microsys.fax.agent.utils;importjava.awt.image.BufferedImage;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileNotFoundException;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importjava.io.OutputStream;importjava.util.ArrayList;importjava.util.List;importjavax.media.jai.JAI;importjavax.media.jai.PlanarImage;importorg.apache.pdfbox.pdmodel.PDDocument;importorg.apache.pdfbox.rendering.ImageType;importorg.apache.pdfbox.rendering.PDFRenderer;importcom.jacob.activeX.ActiveXComponent;importcom.jacob.com.ComThread;importcom.jacob.com.Dispatch;importcom.jacob.com.Variant;importcom.sun.media.jai.codec.ImageCodec;importcom.sun.media.jai.codec.ImageEncoder;importcom.sun.media.jai.codec.TIFFEncodeParam;/***
* 将jacob.dll放入JDK的bin目录下 把jacob.jar放入项目的buildPath中(web项目放到WEB-INF\lib目录下)
*
**/
public classConvertToPdf {/*转PDF格式值*/
private static final int wdFormatPDF = 17;private static final int xlFormatPDF = 0;private static final int ppFormatPDF = 32;private static final int msoTrue = -1;private static final int msofalse = 0;/*转HTML格式值*/
private static final int wdFormatHTML = 8;private static final int ppFormatHTML = 12;private static final int xlFormatHTML = 44;/*转TXT格式值*/
private static final int wdFormatTXT = 2;//word相关格式转换PDF
public booleanconvert2PDF(String inputFile, String pdfFile) {
String suffix=getFileSufix(inputFile);
File file= newFile(inputFile);if (!file.exists()) {
Log.debug("文件不存在!");return false;
}if (suffix.equals("pdf")) {
Log.debug("PDF not need to convert!");return false;
}if (suffix.equals("doc") || suffix.equals("docx") || suffix.equals("txt")) {returnword2PDF(inputFile, pdfFile);
}else if (suffix.equals("ppt") || suffix.equals("pptx")) {returnppt2PDF(inputFile, pdfFile);
}else if (suffix.equals("xls") || suffix.equals("xlsx")) {returnexcel2PDF(inputFile, pdfFile);
}else{
Log.debug("文件格式不支持转换!");return false;
}
}/*** 从输入流读取pdf,转化为tiff后写入输出流.
* 参考列表:
*
*
* "http://www.coderanch.com/t/497492/java/java/Convert-PDF-files-Tiff-files"
* >Convert PDF files to Tiff files
*
* "http://www.oracle.com/technetwork/cn/java/javaee/downloads/readme-1-1-2-137176.html"
* >Java(TM) Advanced Imaging API README
*
*
*@paramis
* 输入流,提供pfg内容.
*@paramos
* 输出流.*/
public static booleanpdf2Tiff(InputStream is, OutputStream os) {
PDDocument doc= null;try{
doc=PDDocument.load(is);int pageCount =doc.getNumberOfPages();
PDFRenderer renderer= new PDFRenderer(doc); //根据PDDocument对象创建pdf渲染器
List piList = new ArrayList(pageCount - 1);for (int i = 0 + 1; i < pageCount; i++) {
BufferedImage image=renderer.renderImageWithDPI(i, Pdf2TiffConstant.DPI,
ImageType.RGB);
PlanarImage pimg= JAI.create("mosaic", image);
piList.add(pimg);
}
TIFFEncodeParam param= new TIFFEncodeParam();//创建tiff编码参数类
param.setCompression(TIFFEncodeParam.COMPRESSION_DEFLATE);//压缩参数
param.setExtraImages(piList.iterator());//设置图片的迭代器
BufferedImage fimg= renderer.renderImageWithDPI(0, Pdf2TiffConstant.DPI,
ImageType.RGB);
PlanarImage fpi= JAI.create("mosaic", fimg); //通过JAI的create()方法实例化jai的图片对象
ImageEncoder enc=ImageCodec.createImageEncoder(Pdf2TiffConstant.IMG_FORMAT, os,
param);
enc.encode(fpi);//指定第一个进行编码的jai图片对象,并将输出写入到与此
Log.debug("转换文档 [PDF] >>> [Tiff]");return true;
}catch(IOException e) {
e.printStackTrace();
}finally{try{if (doc != null)
doc.close();
}catch(IOException e) {
e.printStackTrace();
}
}return false;
}/*** 获取文件后缀
*
*@paramfileName
*@return*@authorSHANHY*/
privateString getFileSufix(String fileName) {int splitIndex = fileName.lastIndexOf(".");return fileName.substring(splitIndex + 1);
}/*** Word文档转换
*
*@paraminputFile
*@parampdfFile
*@authorSHANHY*/
private booleanword2PDF(String inputFile, String pdfFile) {
ComThread.InitSTA();long start =System.currentTimeMillis();
ActiveXComponent app= null;
Dispatch doc= null;try{
app= new ActiveXComponent("Word.Application");//创建一个word对象
app.setProperty("Visible", new Variant(false)); //不可见打开word
app.setProperty("AutomationSecurity", new Variant(3)); //禁用宏
Dispatch docs = app.getProperty("Documents").toDispatch();//获取文挡属性
Log.debug("打开文档 >>> " +inputFile);//Object[]第三个参数是表示“是否只读方式打开”//调用Documents对象中Open方法打开文档,并返回打开的文档对象Document
doc = Dispatch.call(docs, "Open", inputFile, false, true).toDispatch();//调用Document对象的SaveAs方法,将文档保存为pdf格式
Log.debug("转换文档 [" + inputFile + "] >>> [" + pdfFile + "]");
Dispatch.call(doc,"SaveAs", pdfFile, wdFormatPDF);//word保存为pdf格式宏,值为17//Dispatch.call(doc, "ExportAsFixedFormat", pdfFile, wdFormatPDF);//word保存为pdf格式宏,值为17
long end =System.currentTimeMillis();
Log.debug("用时:" + (end - start) + "ms.");return true;
}catch(Exception e) {
e.printStackTrace();
Log.debug("========Error:Word文档转换失败:" +e.getMessage());
}finally{
Dispatch.call(doc,"Close", false);
Log.debug("关闭文档");if (app != null)
app.invoke("Quit", newVariant[] {});
}//如果没有这句话,winword.exe进程将不会关闭
ComThread.Release();
ComThread.quitMainSTA();return false;
}/*** PPT文档转换
*
*@paraminputFile
*@parampdfFile
*@authorSHANHY*/
private booleanppt2PDF(String inputFile, String pdfFile) {
ComThread.InitSTA();long start =System.currentTimeMillis();
ActiveXComponent app= null;
Dispatch ppt= null;try{
app= new ActiveXComponent("PowerPoint.Application");//创建一个PPT对象//app.setProperty("Visible", new Variant(false));//不可见打开(PPT转换不运行隐藏,所以这里要注释掉)//app.setProperty("AutomationSecurity", new Variant(3));//禁用宏
Dispatch ppts = app.getProperty("Presentations").toDispatch();//获取文挡属性
Log.debug("打开文档 >>> " +inputFile);//调用Documents对象中Open方法打开文档,并返回打开的文档对象Document
ppt = Dispatch.call(ppts, "Open", inputFile,true,//ReadOnly
true,//Untitled指定文件是否有标题
false//WithWindow指定文件是否可见
).toDispatch();
Log.debug("转换文档 [" + inputFile + "] >>> [" + pdfFile + "]");
Dispatch.call(ppt,"SaveAs", pdfFile, ppFormatPDF);long end =System.currentTimeMillis();
Log.debug("用时:" + (end - start) + "ms.");return true;
}catch(Exception e) {
e.printStackTrace();
Log.debug("========Error:PPT文档转换失败:" +e.getMessage());
}finally{
Dispatch.call(ppt,"Close");
Log.debug("关闭文档");if (app != null)
app.invoke("Quit", newVariant[] {});
}
ComThread.Release();
ComThread.quitMainSTA();return false;
}/*** Excel文档转换
*
*@paraminputFile
*@parampdfFile
*@authorSHANHY*/
private booleanexcel2PDF(String inputFile, String pdfFile) {
ComThread.InitSTA();long start =System.currentTimeMillis();
ActiveXComponent app= null;
Dispatch excel= null;try{
app= new ActiveXComponent("Excel.Application");//创建一个PPT对象
app.setProperty("Visible", new Variant(false)); //不可见打开//app.setProperty("AutomationSecurity", new Variant(3));//禁用宏
Dispatch excels = app.getProperty("Workbooks").toDispatch();//获取文挡属性
Log.debug("打开文档 >>> " +inputFile);//调用Documents对象中Open方法打开文档,并返回打开的文档对象Document
excel = Dispatch.call(excels, "Open", inputFile, false, true).toDispatch();//调用Document对象方法,将文档保存为pdf格式
Log.debug("转换文档 [" + inputFile + "] >>> [" + pdfFile + "]");//Excel 不能调用SaveAs方法
Dispatch.call(excel, "ExportAsFixedFormat", xlFormatPDF, pdfFile);long end =System.currentTimeMillis();
Log.debug("用时:" + (end - start) + "ms.");return true;
}catch(Exception e) {
e.printStackTrace();
Log.debug("========Error:Excel文档转换失败:" +e.getMessage());
}finally{
Dispatch.call(excel,"Close", false);
Log.debug("关闭文档");if (app != null)
app.invoke("Quit", newVariant[] {});
}
ComThread.Release();
ComThread.quitMainSTA();return false;
}/*** 测试
*
*@paramargs
*@authorSHANHY*/
public static voidmain(String[] args) {
ConvertToPdf d= newConvertToPdf();//d.convert2PDF("F:\\20170802.docx", "F:\\test.pdf");
d.convert2PDF("F:\\UCS新增功能说明.txt", "F:\\UCS新增功能说明.pdf");//d.convert2PDF("g:\\testppt.pptx", "g:\\testppt.pdf");
/// d.convert2PDF("F:\\bbbbb.xls", "F:\\bbb.pdf");
try{
InputStream is= new FileInputStream(new File("F:\\UCS新增功能说明.pdf"));
File out= new File("F:\\UCS新增功能说明.tiff");if (!out.exists()) {
out.createNewFile();
}
OutputStream os= newFileOutputStream(out);boolean f=pdf2Tiff(is, os);
System.out.println("f:" +f);
is.close();
os.close();
}catch(FileNotFoundException e) {
e.printStackTrace();
}catch(IOException e) {//TODO Auto-generated catch block
e.printStackTrace();
}
}
}