由于从客户有可能上传各中类型的附件,那么在客户实现在线阅览就必须统一格式。基本实现方式就是把所有各种类型文件转换成pdf。然后使用SWFTool把pdf转换成.swf播放文件。在客户端安装flash播放控件(参考:http://blog.csdn.net/u013294278/article/details/76242266)。

那么转换pdf的方式网上有很多种,包括收费与免费的。用过金格pdf转换性能一般。思考既然国内WPS做的那么强大,是否调用WPS组件服务来完成pdf的装换。经过百度谷歌,找到了答案,采用jacob。WPS是提供了组件调用服务。请看以下步骤。

先下载相关依赖:jacob.jar、jacob.dll(注意操作系统32位:jacobx86.dll;64位:jacobx64.dll)

jacob.jar下载地址:http://download.csdn.net/download/u013294278/9979052

jacob.dll下载地址:http://download.csdn.net/download/u013294278/9979224

如果你还想把图片转换成pdf,pdf转换成图片还得下载com.lowagie.text-2.1.7.jar 、PDFRenderer.jar

com.lowagie.text-2.1.7.jar下载地址:http://download.csdn.net/download/u013294278/9979041

PDFRenderer.jar 下载地址: http://download.csdn.net/download/u013294278/9979059

下载好相关依赖之后。新建java工程把所有jar都添加到lib目录。jacob.dll放在jdk/bin目录或者c:/windows/system32/。

以下就是调用WPS组件服务来完成pdf的转换

package org.pdf.tyl.convert;

import java.awt.Color;
import java.awt.Rectangle;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.lang.reflect.Method;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.AccessController;
import java.security.PrivilegedAction;

import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.ColumnText;
import com.lowagie.text.pdf.PdfContentByte;
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;

/**
 * ClassName: PdfConvertUtil pdf装换工具类
 * 
 * @Description:
 * @author JornTang
 * @email 957707261@qq.com
 * @date 2017年9月14日
 */
public class PdfUtil {
// 文档格式转换组件
public static final String WORDSERVER_STRING = "KWPS.Application";
// 幻灯片格式转换组件
public static final String PPTSERVER_STRING = "KWPP.Application";
// 表格格式转换组件
public static final String EXECLSERVER_STRING = "KET.Application";
private static final int wdFormatPDF = 17;
private static final int xlTypePDF = 0;
private static final int ppSaveAsPDF = 32;

public PdfUtil() {
}

/**
* @Description: 文档格式转换 支持 wps、wpt、doc、docx、dot、txt等所有文档格式文件
* @param srcFilePath
*            文档路径
* @param pdfFilePath
*            pdf路径
* @return void
* @throws Exception
* @throws
* @author JornTang
* @email 957707261@qq.com
* @date 2017年9月14日
*/
public static boolean wpsTopdf(String srcFilePath, String pdfFilePath)
throws Exception {
// wps com
ActiveXComponent pptActiveXComponent = null;
ActiveXComponent workbook = null;
// open thred
ComThread.InitSTA();
try {
pptActiveXComponent = new ActiveXComponent(PPTSERVER_STRING);
Variant openParams[] = { new Variant(srcFilePath),
new Variant(true), new Variant(true) };
workbook = pptActiveXComponent.invokeGetComponent("Documents")
.invokeGetComponent("Open", openParams);
workbook.invoke("SaveAs", new Variant[] { new Variant(pdfFilePath),
new Variant(wdFormatPDF) });
} catch (Exception e) {
throw e;
} finally {
if (workbook != null) {
workbook.invoke("Close");
workbook.safeRelease();
}
if (pptActiveXComponent != null) {
pptActiveXComponent.invoke("Quit");
pptActiveXComponent.safeRelease();
}
// close thred
ComThread.Release();
}
return true;
}

/**
* @Description: 幻灯片格式转换 支持ppt、pps、pptx、ppsx、dps、dpt、pot、uof
* @param srcFilePath
*            幻灯片路径
* @param pdfFilePath
*            pdf路径
* @return
* @return boolean
* @throws
* @author JornTang
* @date 2017年9月14日
*/
public static boolean pptTopdf(String srcFilePath, String pdfFilePath) {
ActiveXComponent pptActiveXComponent = null;
ActiveXComponent workbook = null;
boolean readonly = true;
ComThread.InitSTA();
try {
pptActiveXComponent = new ActiveXComponent(PPTSERVER_STRING);
workbook = pptActiveXComponent.invokeGetComponent("Presentations")
.invokeGetComponent(
"Open",
new Variant[] { new Variant(srcFilePath),
new Variant(readonly) });
workbook.invoke("SaveAs", new Variant[] { new Variant(pdfFilePath),
new Variant(ppSaveAsPDF) });
return true;
} catch (Exception e) {
throw e;
} finally {
if (workbook != null) {
workbook.invoke("Close");
workbook.safeRelease();
}
if (pptActiveXComponent != null) {
pptActiveXComponent.invoke("Quit");
pptActiveXComponent.safeRelease();
}
ComThread.Release();
}
}

/**
* @Description: 表格格式转换 支持et、ett、xls、xlsx、xlt、uof、prn、csv
* @param srcFilePath
*            幻灯片路径
* @param pdfFilePath
*            pdf路径
* @return
* @return boolean
* @throws
* @author JornTang
* @date 2017年9月14日
*/
public static boolean xlsTopdf(String srcFilePath, String pdfFilePath) {
ActiveXComponent et = null;
Dispatch workbook = null;
workbook = null;
ComThread.InitSTA();
try {
et = new ActiveXComponent(EXECLSERVER_STRING);
et.setProperty("Visible", new Variant(false));
Dispatch workbooks = et.getProperty("Workbooks").toDispatch();
workbook = Dispatch.invoke(
workbooks,
"Open",
1,
new Object[] { srcFilePath, Integer.valueOf(xlTypePDF),
Boolean.valueOf(true) }, new int[1]).toDispatch();
Dispatch.call(workbook, "ExportAsFixedFormat", new Object[] {
Integer.valueOf(xlTypePDF), pdfFilePath });
return true;
} catch (Exception e) {
throw e;
} finally {
if (workbook != null) {
Dispatch.call(workbook, "Close");
workbook.safeRelease();
}
if (et != null) {
et.invoke("Quit");
et.safeRelease();
}
ComThread.Release();
}
}

/**
* @Description: 图片转pdf
* @param imagePath
* @param pdfFilePath
* @return
* @return boolean
* @throws DocumentException
* @throws IOException
* @throws
* @author JornTang
* @date 2017年9月14日
*/
public static boolean iamgeTopdf(String imagePath, String pdfFilePath)
throws DocumentException, IOException {
File pdfFile = new File(pdfFilePath);
if (pdfFile.exists()) {
throw new FileNotFoundException("pdfFilePath already exists");
}
Document doc = new Document(PageSize.A4, 20, 20, 20, 20);
try {
PdfWriter.getInstance(doc, new FileOutputStream(
pdfFilePath));
doc.open();

doc.newPage();
Image png1 = Image.getInstance(imagePath);
float heigth = png1.getHeight();
float width = png1.getWidth();
int percent = getPercent(heigth, width);
png1.setAlignment(Image.MIDDLE);
png1.setAlignment(Image.TEXTWRAP);
png1.scalePercent(percent + 3);
doc.add(png1);
//handleText(writer, "This is a test", "red", 400, 725, 0);
doc.close();
return true;
} catch (FileNotFoundException e) {
throw e;
} catch (DocumentException e) {
throw e;
} catch (IOException e) {
throw e;
}
}
/**
* @Description: 添加文字
* @param writer
* @param content
* @param color
* @param x
* @param y
* @param z   
* @return void  
* @throws
* @author JornTang
* @date 2017年9月14日
*/
private static void handleText(PdfWriter writer, String content, String color,
float x, float y, float z) {
PdfContentByte canvas = writer.getDirectContent();
Phrase phrase = new Phrase(content);
if (color != null) {
phrase = new Phrase(content, FontFactory.getFont(
FontFactory.COURIER, 12, Font.NORMAL, new Color(255, 0, 0)));
}

ColumnText.showTextAligned(canvas, Element.ALIGN_UNDEFINED, phrase, x,
y, z);
}
/**
* @Description: 在不改变图片形状的同时,判断,如果h>w,则按h压缩,否则在w>h或w=h的情况下,按宽度压缩
* @param h
* @param w
* @return   
* @return int  
* @throws
* @author JornTang
* @date 2017年9月14日
*/
public static int getPercent1(float h, float w) {
int p = 0;
float p2 = 0.0f;
if (h > w) {
p2 = 297 / h * 100;
} else {
p2 = 210 / w * 100;
}
p = Math.round(p2);
return p;
}
/**
* @Description: 统一按照宽度压缩 这样来的效果是,所有图片的宽度是相等的,自我认为给客户的效果是最好的 
* @param h
* @param w
* @return   
* @return int  
* @throws
* @author JornTang
* @date 2017年9月14日
*/
private static int getPercent(float h, float w) {
int p = 0;
float p2 = 0.0f;
p2 = 530 / w * 100;
p = Math.round(p2);
return p;
}

/**
* @Description: pdf转图片
* @param pdfFilePath
* @param imageFilePath
* @throws IOException
* @return void
* @throws
* @author JornTang
* @date 2017年9月14日
*/
public static void pdfTojpg(String pdfFilePath, String imageFilePath)
throws Exception {
ByteBuffer buf = null;
RandomAccessFile raf = null;
FileChannel channel = null;
try {
// load a pdf from a byte buffer
File file = new File(pdfFilePath);
raf = new RandomAccessFile(file, "r");
channel = raf.getChannel();
// 这句代码通道建立了map映射,如果要删除file那么得接触映射
buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);
int totalpage = pdffile.getNumPages();
for (int i = 1; i <= totalpage; i++) {
if (i == 1) {
// draw the first page to an image
// 以图片的形式来描绘首页
PDFPage page = pdffile.getPage(i);
Rectangle rect = new Rectangle(0, 0, (int) page.getBBox()
.getWidth(), (int) page.getBBox().getHeight());
// generate the image
// 生成图片
java.awt.Image img = page.getImage(rect.width, rect.height, // width
// &
// height
rect, // clip rect
null, // null for the ImageObserver
true, // fill background with white
true // block until drawing is done
);
BufferedImage tag = new BufferedImage(rect.width,
rect.height, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(
img.getScaledInstance(rect.width, rect.height,
java.awt.Image.SCALE_SMOOTH), 0, 0, rect.width,
rect.height, null);

FileOutputStream out = new FileOutputStream(imageFilePath); // 输出到文件流
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
encoder.encode(tag); // JPEG编码
// 关闭输出流
out.close();
break;
}
}
} catch (Exception e) {
throw e;
} finally {
buf.clear();
channel.close();
raf.close();
unmap(buf);
}
}

/**
* @Description: 解除map映射
* @param buffer
* @return void
* @throws
* @author JornTang
* @date 2017年9月14日
*/
public static <T> void unmap(final Object buffer) {
AccessController.doPrivileged(new PrivilegedAction<T>() {
@Override
public T run() {
try {
Method getCleanerMethod = buffer.getClass().getMethod(
"cleaner", new Class[0]);
getCleanerMethod.setAccessible(true);
sun.misc.Cleaner cleaner = (sun.misc.Cleaner) getCleanerMethod
.invoke(buffer, new Object[0]);
cleaner.clean();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
});
}

public static void main(String[] args) {
try {
xlsTopdf("E:\\FileTest\\testxls.xlsx",
"E:\\FileTest\\11111111xls.pdf");
} catch (Exception e) {
e.printStackTrace();
}
}
}

调用WPS服务COM组件转换PDF相关推荐

  1. Python调用WPS进行文档转换PDF及PDF转图片

    这里是利用WPS进行转换,要先安装WPS. 安装依赖 pip install pypiwin32 代码 #!/usr/bin/python # -*- coding: UTF-8 -*-import ...

  2. C#调用WPS转换文档到PDF的的实现代码。

    C#调用WPS转换文档到PDF的的实现代码. 1.WPS安装,最好用这个版本别的版本不清楚,安装Pro Plus2016版本. https://ep.wps.cn/product/wps-office ...

  3. Java 使用wps将word文件转换pdf文件

    public class WordFileToPdf {private static final int wdFormatPDF = 17;private static final int xlTyp ...

  4. 通过Jacob调用WPS将office文件转为PDF文件

    访问https://sourceforge.net/projects/jacob-project/ 想要调启Windows里的程序需要对应的dll库,下载之后解压 将符合你电脑的dll文件复制到jdk ...

  5. C#调用GhostScript,O2S.Components转换PDF为图片

    方法一:使用O2S.Components.PDFRENDER4net.DLL https://jingyan.baidu.com/article/47a29f2453ab72c015239946.ht ...

  6. kotlin中mainactivity无法直接调用xml中的控件_使用52North 客户端接口调用OGC WPS服务...

    52°North是一个来自研究机构.工业界和公共行政管理界的研究者组成的开放国际合作组织,他们通过协作研发流程促进地理信息学创新.具体来说他们开发新的地理信息概念和技术,例如用于管理时空测量数据,以及 ...

  7. SharePoint 2013 Word 转换PDF服务介绍及示例

    前言:在SharePoint使用过程中,经常会发现将文档进行格式转换的需求,之前,看到SharePoint 2013有将PPT转换PDF文档的服务,后来,才发现SharePoint 2010开始,就有 ...

  8. java调用libreoffice_JAVA实现LibreOffice转换PDF文档

    首先,安装LibreOffice服务 使用.LibreOfficeAndJodconverter.java package com.jalor.LibreOffice; import java.io. ...

  9. WPS怎么转换PDF?保证你一学就会

    相信大家在处理文件的时候肯定会使用到WPS文件,WPS文件包括Word.Excel.PPT文件,是我们经常使用的几种文件,有这几种文件我们可以更好的完成工作,但是在有些情况下,我们需要将WPS转换成P ...

最新文章

  1. NOIP模拟 蛋糕(DP+Dilworth定理)
  2. 确认过眼神(*╹▽╹*),这就是大家想要的BCH
  3. mysql-视图,触发器,事物,函数,存储过程
  4. 201521123009 《Java程序设计》第12周学习总结
  5. linux 内核升级 网络 不能上网,Deepin Linux 无法上网
  6. java方法生命周期_java – Servlet的生命周期及其方法
  7. 人脸识别(二)——训练分类器
  8. Java实现目的选层电梯的调度
  9. 使用Chrome打开http://www.cutv.com/demo/live_test.swf页面时swf文件自动下载问题
  10. zabbix setup.php出错,apache配置zabbix下setup.php无法显示
  11. JDK环境变量设置(linux)
  12. We7提供电子政务信息公开最佳方案
  13. python 绘制简易折线图
  14. Java基础语法(基本语句)
  15. 光纤尾纤的型号和作用有哪些?
  16. H3C AP当无线路由器静态IP上网配置
  17. vld在MFC 中内存泄漏检测
  18. 如何给无光驱无软驱无USB启动的老笔记本装系统
  19. 一年前,没有Android,我还是一个游戏开发者
  20. android svg 线条动画教程,简单的SVG线条动画

热门文章

  1. 如何言语上更好的激励别人?
  2. HDFS 的深入了解,深入浅出,面试必备(Hadoop的三部曲——上)
  3. 如何用Scrum做变革管理的落地实施
  4. 大数据学习之路 JUC篇
  5. mysql数据的复制与恢复_MySQL 数据库的备份与恢复
  6. 使用时testng报错问题解决方案
  7. excel 的选择性粘贴
  8. 软件测试-测试面试题
  9. 【MySQL笔记】视图的创建与使用(VIEW)
  10. linux ps被替换文件,在linux下从jar中替换、修改文件