office(word,execel,ppt)转换为图片输出
Posted lljliulljn
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了office(word,execel,ppt)转换为图片输出相关的知识,希望对你有一定的参考价值。
import com.jetsen.convert.utils.OfficeToPDF;
import com.jetsen.convert.utils.PdfConvertImg;
/**
*
* =============================================================================
* 类型名称: Convert2Img
* 类型版本: V1.0
* 类型作者: jinchao
* 创建日期: 2016年8月4日
* 类型备注: ms 文档转为图片
* =============================================================================
*/
public class Convert2Img
public static boolean docConvertImg(String inputFileName)
boolean convert2pdf = OfficeToPDF.saveOfficeAsPDF(inputFileName);
if(convert2pdf)
String pdfFileName = inputFileName.substring(0, inputFileName.lastIndexOf(“.”));
boolean convert2Img = PdfConvertImg.convert2Img(pdfFileName);
if(convert2Img)
return true;
else
return false;
else
return false;
public static void main(String[] args)
Convert2Img.docConvertImg("new资源试题库API(7).docx");
Convert2Img.docConvertImg("靳超-八月份考勤.xlsx");
import java.io.File;
public class FilePathUtils
public static String getFileSufix(String fileName)
int splitIndex = fileName.lastIndexOf(".");
return fileName.substring(splitIndex + 1);
public static String getFilePrefix(String filePath)
//获取文件名称(不包含路径部分)
int splitIndex1 = filePath.lastIndexOf("/");
if(splitIndex1!=-1)
String fileName = filePath.substring(splitIndex1+1);
int splitIndex2 = fileName.lastIndexOf(".");
return fileName.substring(0,splitIndex2);
else
return filePath.substring(0,filePath.lastIndexOf("."));
public static void mkdir(String dir)
File fileDir = new File(dir);
if(!fileDir .exists() && !fileDir .isDirectory())
fileDir .mkdir();
public static void deleteAll(File file)
if(file.isDirectory())
for(File f:file.listFiles())
if(f.isDirectory())
deleteAll(f);
else
f.delete();
file.delete();
import java.io.File;
import java.util.Iterator;
import com.jacob.activeX.ActiveXComponent;
import com.jacob.com.ComThread;
import com.jacob.com.Dispatch;
import com.jacob.com.Variant;
/**
*
* =============================================================================
* 类型名称: OfficeToPDF
* 类型版本: V1.0
* 类型作者: jinchao
* 创建日期: 2016年8月8日
* 类型备注:
* =============================================================================
*/
@SuppressWarnings(“static-access”)
public class OfficeToPDF
private static final int wdFormatPDF = 17;
//private static final int xlTypePDF = 0;
private static final int ppSaveAsPDF = 32;
private static ActiveXComponent wordCom = null;
private static ActiveXComponent execelCom = null;
private static ActiveXComponent pptCom = null;
public static boolean saveOfficeAsPDF(String filePath)
boolean flag = false;
ComThread.InitSTA();
String suffix = FilePathUtils.getFileSufix(filePath);
String inputFile = PropertyConfig.pc.getProperty("office_dir")+filePath;
File file = new File(inputFile);
if(!file.exists())
System.out.println("文件不存在!");
return false;
if(suffix.equals("pdf"))
System.out.println("PDF not need to convert!");
return false;
String outputFile = PropertyConfig.pc.getProperty("pdf_dir")+FilePathUtils.getFilePrefix(inputFile)+"/";
File outFileDir = new File(outputFile);
FilePathUtils.deleteAll(outFileDir);
FilePathUtils.mkdir(outputFile);
String outFile = outputFile+FilePathUtils.getFilePrefix(inputFile)+".pdf";//pdf文件输出路径及文件名称
try
if(suffix.equals("doc")||suffix.equals("docx"))
wordCom=new ActiveXComponent("Word.Application");
Dispatch wrdDocs=Dispatch.get(wordCom,"Documents").toDispatch();
Dispatch wordDoc=Dispatch.call(wrdDocs,"Open",inputFile,
new Variant(true),new Variant(false)).toDispatch();
Dispatch.invoke(wordDoc,"ExportAsFixedFormat",Dispatch.Method,new Object[]
outFile,new Variant(17),new Variant(false),new Variant(0),new Variant(0),
new Variant(0),new Variant(0),new Variant(false),new Variant(true),
new Variant(0),new Variant(false),new Variant(true),new Variant(false),new int[0]);
flag = true;
//Dispatch.call(wordDoc, "Close",new Variant(false));
// wordCom = new ActiveXComponent(“Word.Application”);
// wordCom.setProperty(“Visible”, false);
// Dispatch docs = wordCom.getProperty(“Documents”).toDispatch();
// Dispatch doc = Dispatch.invoke(docs, “Open”, Dispatch.Method,
// new Object[] inputFile,new Variant(false),new Variant(true),new Variant(false),new Variant(“pwd”) ,
// new int[1]).toDispatch();
Dispatch.put(doc, “Compatibility”, false); //兼容性检查,为特定值false不正确
// Dispatch.put(doc, “RemovePersonalInformation”, false);
// Dispatch.call(doc, “ExportAsFixedFormat”, outFile, wdFormatPDF); // word保存为pdf格式宏,值为17
// flag = true;
else if(suffix.equals(“xls”)||suffix.equals(“xlsx”))
execelCom = new ActiveXComponent(“Excel.Application”);
execelCom.setProperty(“Visible”, new Variant(false));
execelCom.setProperty(“AutomationSecurity”, new Variant(3)); //禁用宏
Dispatch excels=execelCom.getProperty(“Workbooks”).toDispatch();
Dispatch excel=Dispatch.invoke(excels,”Open”,Dispatch.Method,new Object[]inputFile, new Variant(false), new Variant(false),new int[9]).toDispatch();
Dispatch.invoke(excel,”ExportAsFixedFormat”,Dispatch.Method,new Object[]new Variant(0),outFile,new Variant(0),new int[1]);
Dispatch.call(excel, “Close”,new Variant(false));
flag = true;
else if(suffix.equals(“ppt”)||suffix.equals(“pptx”))
pptCom = new ActiveXComponent(“PowerPoint.Application”);
Dispatch ppts = pptCom.getProperty(“Presentations”).toDispatch();
Dispatch ppt = Dispatch.call(ppts, “Open”, inputFile, true,true,false).toDispatch();
Dispatch.call(ppt, “SaveAs”, outFile, ppSaveAsPDF);
flag = true;
else
System.out.println(“文件格式不支持转换!”);
flag = false;
return flag;
catch (Exception es)
es.printStackTrace();
return false;
finally
if(suffix.equals("doc")||suffix.equals("docx"))
closeWord(false);
if(suffix.equals("xls")||suffix.equals("xlsx"))
closeExecel(false);
if(suffix.equals("ppt")||suffix.equals("pptx"))
closePPT(false);
public static void closeWord(boolean saveOnExit)
if (wordCom != null)
wordCom.invoke("Quit", new Variant[] );
wordCom = null;
ComThread.Release();
public static void closeExecel(boolean saveOnExit)
if (execelCom != null)
execelCom.invoke("Quit", new Variant[] );
execelCom = null;
ComThread.Release();
public static void closePPT(boolean saveOnExit)
if (pptCom != null)
pptCom.invoke("Quit", new Variant[] );
pptCom = null;
ComThread.Release();
public static void main(String[] args)
OfficeToPDF off = new OfficeToPDF();
String filePath1 = "new资源试题库API(7).docx";
String filePath2 = "靳超-八月份考勤.xlsx";
boolean flag1 = off.saveOfficeAsPDF(filePath1);
//boolean flag2 = off.saveOfficeAsPDF(filePath2);
System.out.println(flag1);
//System.out.println(flag2);
import java.awt.Image;
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.MappedByteBuffer;
import java.nio.channels.FileChannel;
import java.security.AccessController;
import java.security.PrivilegedAction;
import com.sun.image.codec.jpeg.JPEGCodec;
import com.sun.image.codec.jpeg.JPEGEncodeParam;
import com.sun.image.codec.jpeg.JPEGImageEncoder;
import com.sun.pdfview.PDFFile;
import com.sun.pdfview.PDFPage;
/**
*
* =============================================================================
* 类型名称: PdfConvertImg
* 类型版本: V1.0
* 类型作者: jinchao
* 创建日期: 2016年8月4日
* 类型备注: PDF文件转换为图片
* =============================================================================
*/
@SuppressWarnings(“unchecked”,”rawtypes”,”static-access”)
public class PdfConvertImg
public static boolean convert2Img(String inputFileName)
try
//PDF存放路径
String inputPdfDir = PropertyConfig.pc.getProperty("pdf_dir")+inputFileName+"/";
//创建图片输出目录
String outputImgDir = PropertyConfig.pc.getProperty("img_out_dir")+inputFileName+"/";
FilePathUtils.deleteAll(new File(outputImgDir));
FilePathUtils.mkdir(outputImgDir);
//图片输出路径
File inputFileDirectory = new File(inputPdfDir+inputFileName+".pdf");
RandomAccessFile raf = new RandomAccessFile(inputFileDirectory, "r");
FileChannel channel = raf.getChannel();
MappedByteBuffer buf = channel.map(FileChannel.MapMode.READ_ONLY, 0, channel.size());
PDFFile pdffile = new PDFFile(buf);
for (int i = 1; i <= pdffile.getNumPages(); i++)
PDFPage page = pdffile.getPage(i);
Rectangle rect = new Rectangle(0, 0, ((int) page.getBBox().getWidth()),((int) page.getBBox().getHeight()));
Image img = page.getImage(rect.width*2, rect.height*2, rect, null, true, true);
BufferedImage tag = new BufferedImage(rect.width*2, rect.height*2, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(img, 0, 0, rect.width*2, rect.height*2, null);
FileOutputStream out = new FileOutputStream(outputImgDir+ i + ".jpg");
JPEGImageEncoder encoder = JPEGCodec.createJPEGEncoder(out);
JPEGEncodeParam param2 = encoder.getDefaultJPEGEncodeParam(tag);
param2.setQuality(1f, true);// 1f是提高生成的图片质量
encoder.setJPEGEncodeParam(param2);
encoder.encode(tag); // JPEG编码
out.close();
channel.close();
raf.close();
unmap(buf);
return true;
catch (FileNotFoundException e)
e.printStackTrace();
return false;
catch (IOException e)
e.printStackTrace();
return false;
private static void unmap(final Object buffer)
AccessController.doPrivileged(new PrivilegedAction()
public Object 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)
return null;
);
public static void main(String[] args)
convert2Img("new资源试题库API(7).pdf");
convert2Img("靳超-八月份考勤.xlsx");
convert2Img("我是PPT.pptx");
import java.util.Properties;
/**
* PropertyConfig 工具类
* @author HuaiY
*/
@SuppressWarnings(“static-access”)
public class PropertyConfig
//private static Log logger = LogFactory.getLog(PropertyConfig.class);
public static PropertyConfig pc = new PropertyConfig();
public Properties properties = null;
private PropertyConfig()
this.loadConfig();
public static PropertyConfig getInstance()
if (pc == null)
pc = new PropertyConfig();
return pc;
public static String getProperty(String name)
return pc.properties.getProperty(name);
public void loadConfig()
try
properties = new Properties();
properties.load(getClass().getResourceAsStream("/business.properties"));
//logger.info("loading business.properties...... ");
catch (Exception e)
//logger.error("load business.properties error: "+ e.toString());
e.printStackTrace();
/**
* @param args
*/
public static void main(String[] args)
System.out.println(PropertyConfig.pc.getProperty("FIND_CLASS_URL"));
以上是关于office(word,execel,ppt)转换为图片输出的主要内容,如果未能解决你的问题,请参考以下文章
Atitit.office word excel ppt pdf 的web在线预览方案与html转换方案 attil
Office Open XML文档怎么转换成word文档 2003的
话说office 2010 word文档和PPT是可以转化成PDF文档的,为啥我的word转化过来后乱码了?怎么破?谢谢~~