调用WPS服务COM组件转换PDF

由于从客户有可能上传各中类型的附件,那么在客户实现在线阅览就必须统一格式。基本实现方式就是把所有各种类型文件转换成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();
}
}
}






  • 1
    点赞
  • 13
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
### 回答1: Java WPSPDF是指使用Java编程语言编写一个程序,通过调用WPS Office软件中的API,将WPS文档转换PDF文档。WPS Office作为一款办公软件,支持多种文档格式的打开和编辑,如.doc、.ppt、.xls等,但有时候需要将这些文档转换PDF格式,以供更广泛的使用和分享。 Java作为一种跨平台的编程语言,可以在不同的操作系统和设备上运行,具有很强的可移植性和灵活性,因此选择Java编写该程序可以满足这些需求。该程序可以实现WPS文档与PDF之间的格式转换,并可以在不同的操作系统和平台上运行,同时可以在程序中设置转换的参数,如文档的页面大小、分辨率、文本字体等。 通过编写该程序,可以实现WPS文档的批量转换,并可以自动化处理多个文档的转换过程,提高效率和减少人工干预。此外,该程序还可以对转换后的PDF文档进行一些处理,如加密、签名、压缩等,以增强文档的安全性和保密性。 总之,Java WPSPDF程序是一种实用的工具,可以方便地将WPS文档转换PDF文档,并可以在不同的平台和场景下灵活运用。 ### 回答2: Java WPSPDF是指使用Java程序对WPS文件进行转换,将其转成PDF格式。WPS是一种办公文档文件格式,它是金山软件公司开发的,与Microsoft Office的DOC格式兼容。WPS可以在Windows、Mac和Linux上运行,非常方便。但是,有时需要将WPS文件转换PDF格式,以便在各种设备上进行阅读和打印。 Java是一种广泛使用的编程语言,它具有跨平台性。使用Java WPSPDF程序,可以在不同的操作系统上运行。该程序将WPS文件转换PDF格式,保留WPS文件原有的格式和内容。转换完成后,生成的PDF文件可以在各种设备上进行阅读和打印,如PC、手机和平板电脑。 Java WPSPDF程序可以应用于各种场景,如在企业中共享文档、在学校中分享学习资料、在家庭中打印或阅读电子书等等。通过Java WPSPDF程序,可以使文件的传输和共享更加便捷,提高工作效率和学习效果。 ### 回答3: Java语言可以通过调用WPS API实现将WPS文档转换PDFWPS API提供了WPS文档转换的功能,支持多种文档格式的转换,包括WPS、DOC、DOCX、XLS、XLSX、PPT、PPTX等。Java程序可以调用WPS API提供的接口,将WPS文档加载为WPS API中的文档对象,然后使用WPS API提供的转换功能将文档转换PDF格式。在转换过程中,可以通过设置转换参数,如转换后的PDF文件名、是否保留原文件等,来实现不同的转换需求。需要注意的是,Java程序需要在运行环境中安装相关的WPS软件才能调用WPS API进行文档转换

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

档案小唐总

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值