使用 aspose 框架实现ex转pdf,图片。word转pdf,图片。pdf转图片
下载好相应的 aspose 的jar包加入maven依赖就可以直接使用,不过aspose项目是收费项目在官网需要花钱购买。不想花钱的朋友也可以在网上找找破解版本
在使用中发现如果直接使用ex表格转图片或者直接使用word文件转图片。可能会存在格式上的差异。但是如果想将ex文件或者word文件转为pdf文件在转图片的话,就不会存在这样的差异。
经测试该代码和jar包都可以在linux系统上使用,但是要注意如果文件中存在中文,而linux系统中又不曾安装中文字体,转换出来的效果会不尽人意。下面附一个中文字体的包可以安装到linux上,请自行下载
中文字体包
话不多说下面附上代码
package com.utils;import com.aspose.cells.*;import com.aspose.words.*;import com.aspose.words.ImageSaveOptions;import com.aspose.words.License;import com.aspose.words.SaveFormat;import org.apache.pdfbox.pdmodel.PDDocument;import org.apache.pdfbox.rendering.PDFRenderer;import org.apache.poi.ss.formula.functions.T;import javax.imageio.ImageIO;import java.awt.image.BufferedImage;import java.io.*;import .MalformedURLException;import .URL;import .URLConnection;import java.util.ArrayList;import java.util.List;public class WordtoPngUtils {static int flag = 1;//用来判断文件是否删除成功/*** licence 验证* @return* @throws Exception*/public static boolean getLicense() throws Exception {boolean result = false;try {InputStream is = Document.class.getResourceAsStream("/com.aspose.words.lic_2999.xml");License aposeLic = new License();aposeLic.setLicense(is);result = true;is.close();} catch (Exception e) {// logger.error("License 获取失败");e.printStackTrace();throw e;}return result;}/**** @param path 文件地址* @param newFilePath 转换以后的文件地址* @throws Exception*/public static void ExcelToPdf(String path, String newFilePath){String dir = newFilePath.substring(0, newFilePath.lastIndexOf("/") + 1);try {File file=new File(dir);if (!file.exists()) {file.mkdirs();}Workbook excel = null;excel = new Workbook(path);excel.save(newFilePath, com.aspose.cells.SaveFormat.PDF);} catch (Exception e) {e.printStackTrace();}}/*** 转换全部的pdf* @param filename PDF文件名*/public static List<String> pdf2png(String filename) {// 将pdf装图片 并且自定义图片得格式大小List<String> list=new ArrayList<>();String type="jpg";File file = new File(filename);try {PDDocument doc = PDDocument.load(file);PDFRenderer renderer = new PDFRenderer(doc);int pageCount = doc.getNumberOfPages();for (int i = 0; i < pageCount; i++) {BufferedImage image = renderer.renderImageWithDPI(i, 144); // Windows native DPI// BufferedImage srcImage = resize(image, 240, 240);//产生缩略图String img=filename.substring(0,filename.length()-5)+i+"."+type;ImageIO.write(image, type, new File(img));list.add(img);}doc.close();} catch (IOException e) {e.printStackTrace();}return list;}/*** @param filepath .xls或者.xlsx文件的路径* @param picpath jpg或者png图片的路径*/public static void excelToImage (String filepath ,String picpath){Workbook book = null;try {book = new Workbook(filepath);Worksheet sheet = book.getWorksheets().get(0);ImageOrPrintOptions imgOptions = new ImageOrPrintOptions();imgOptions.setImageFormat(ImageFormat.getJpeg());//imgOptions.setChartImageType(ImageFormat.getJpeg());imgOptions.setCellAutoFit(true);imgOptions.setOnePagePerSheet(true);imgOptions.setDefaultFont("200");SheetRender render = new SheetRender(sheet, imgOptions);render.toImage(0, picpath);} catch (Exception e) {e.printStackTrace();}}public static String getDataDir(Class c) {File dir = new File(System.getProperty("user.dir"));// System.out.println("shake" + dir.getAbsolutePath());dir = new File(dir, "src");dir = new File(dir, "main");dir = new File(dir, "resources");for (String s : c.getName().split("\\.")) {dir = new File(dir, s);}if (dir.exists()) {System.out.println("Using data directory: " + dir.toString());} else {dir.mkdirs();System.out.println("Creating data directory: " + dir.toString());}return dir.toString() + File.separator;}/*** 文档转图片* @param inPath 传入文档地址* @param outDir 输出的图片文件夹地址*/public static List<String> doc2Img(String inPath, String outDir) {List<String> list=new ArrayList<>();try {if (!getLicense()) {throw new Exception("com.aspose.words lic ERROR!");}//logger.info(inPath + " -> " + outDir);long old = System.currentTimeMillis();// word文档Document doc = new Document(inPath);// 支持RTF HTML,OpenDocument, PDF,EPUB, XPS转换ImageSaveOptions options = new ImageSaveOptions(SaveFormat.JPEG);int pageCount = doc.getPageCount();for (int i = 0; i < pageCount; i++) {String s=outDir.substring(0,outDir.length()-5) + i + ".jpg";File file = new File(s);list.add(s);//logger.info(outDir + "/" + i + ".png");FileOutputStream os = new FileOutputStream(file);options.setPageIndex(i);doc.save(os, options);os.close();}long now = System.currentTimeMillis();//logger.info("convert OK! " + ((now - old) / 1000.0) + "秒");} catch (Exception e) {e.printStackTrace();}return list;}/*** word转pdf的方法* @param inPath* @param outPath*/public static void doc2pdf(String inPath, String outPath) {System.out.println(inPath + " -> " + outPath);File files=new File(outPath);//如果这个pdf存在就不转换他if (!files.exists()){try {if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档有水印throw new Exception("com.aspose.words lic ERROR!");}long old = System.currentTimeMillis();Document doc = new Document(inPath);File file = new File(outPath);FileOutputStream os = new FileOutputStream(file);// word文档// 支持RTF HTML,OpenDocument, PDF,EPUB, XPS转换doc.save(os, SaveFormat.PDF);os.close();//long now = System.currentTimeMillis();//System.out.println("convert OK! " + ((now - old) / 1000.0) + "秒");} catch (Exception e) {e.printStackTrace();}}}/*** 下载网文件* @param path 资源的路径* @param filepath 文件存放的目录* @param fileip 生成文件最终的地址* @throws MalformedURLException*/public static void downloadNet(String path, String filepath,String fileip) throws MalformedURLException {// 下载网络文件int bytesum = 0;int byteread = 0;URL url = new URL(path);File file=new File(filepath);if (!file.exists()) {file.mkdirs();}File files=new File(fileip);if (!files.exists()){try {URLConnection conn = url.openConnection();InputStream inStream = conn.getInputStream();FileOutputStream fs = new FileOutputStream(fileip);byte[] buffer = new byte[1204];int length;while ((byteread = inStream.read(buffer)) != -1) {bytesum += byteread;// System.out.println(bytesum);fs.write(buffer, 0, byteread);}fs.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}}/*** 删除指定文件* @param file* @return*/public static Boolean deleteFile(File file){//判断文件不为null或文件目录存在if (file == null || !file.exists()){flag = 0;System.out.println("文件删除失败,请检查文件路径是否正确");return true;}//取得这个目录下的所有子文件对象File[] files = file.listFiles();//遍历该目录下的文件对象for (File f: files){//打印文件名String name = file.getName();System.out.println(name);//判断子目录是否存在子目录,如果是文件则删除if (f.isDirectory()){deleteFile(f);}else {f.delete();}}//删除空文件夹 for循环已经把上一层节点的目录清空。file.delete();return true;}/*** 分割文件路径* @param path* @return*/public static String tupath(String path){String[] split = path.split("/");String s="/";for (int i = 0; i < split.length-1; i++) {if (i==split.length-2){s=s+split[i];}else {s=s+split[i]+"/";}}return s;}}
最后加上依赖的aspose 包版本
aspose-words-18.6-jdk16
Aspose-cells-20.4-crack.jar