使用aspose把各种文件转换成pdf

使用aspose把各种文件转换成pdfpackagecom.fh.util;importjava.io.File;importjava.io.FileInputStream;importjava.io.FileOutputStream;importjava.io.IOException;importjava.io.InputStream;importorg.apache.pdfbox.pdmodel.PD…

大家好,又见面了,我是你们的朋友全栈君。

package com.fh.util;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import org.apache.pdfbox.pdmodel.PDDocument;

import com.aspose.cells.Workbook;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Image;
import com.lowagie.text.PageSize;
import com.lowagie.text.pdf.PdfWriter;

/**
 * 
 * 使用的aspose包把文档转换成pdf工具类
 * @author dwm
 *2019-07-03
 */
public class Word2Pdf {
	
	public static void main(String[] args) {
//		excel2Pdf("F:\\aaa\\加班.xls","F:\\aaa\\加班.pdf") ;
	}
	
	 /**
     * 获取pdf文档的页数
     * @param pdfFilePath
     * @return
     */
    public static int getPdfPage(String pdfFilePath){
    	try{
    		// 判断输入文件是否存在
    		File file = new File(pdfFilePath);  
            if (!file.exists()) {  
                return 0;  
            }
            
            // 如果不是pdf直接返回0
            if (!FileUtil.getFileSufix(pdfFilePath).equals("pdf")) {  
                return 0;  
            }
            
            PDDocument pdf = PDDocument.load(file);
            return pdf.getPages().getCount();		//返回页数
            
    	}catch(Exception e){
    		e.printStackTrace();
    		return 0;
    	}
    }
	
	/**
	 * 使用aspose转换成pdf文件
	 * @param inputFile
	 * @param pdfFile
	 * @return
	 */
	public static boolean convertToPdfAsAspose(String inputFile, String pdfFile) {
		String suffix = FileUtil.getFileSufix(inputFile); //后缀
		File file = new File(inputFile) ;
		if(!file.exists()) {
			return false ;
		}
		if("pdf".equalsIgnoreCase(suffix)) {
			return false ;
		}
		
		//根据不同的文件转换成pdf文件
		if("doc".equalsIgnoreCase(suffix) || "docx".equalsIgnoreCase(suffix) || "txt".equalsIgnoreCase(suffix)) {
			return doc2pdf(inputFile,pdfFile) ;
		} else if("xls".equalsIgnoreCase(suffix) || "xlsx".equalsIgnoreCase(suffix)) {
			return excel2Pdf(inputFile, pdfFile);
		} else if("xls".equalsIgnoreCase(suffix) || "xlsx".equalsIgnoreCase(suffix)) {
			return excel2Pdf(inputFile, pdfFile);
		} else if (suffix.equalsIgnoreCase("png") || suffix.equalsIgnoreCase("jpg") 
        		|| suffix.equalsIgnoreCase("jpeg")) {  
            return img2PDF(inputFile, pdfFile);  
        } else {  
            return false;  
        }
	}
	
	/**
	 * aspose.word包获取配置
	 * @return
	 */
	public static boolean getWordLicense() {
        boolean result = false;
        InputStream is = null ;
        try {
        	is = Word2Pdf.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
        	com.aspose.words.License aposeLic = new com.aspose.words.License();
            aposeLic.setLicense(is);
            result = true;
            is.close();
        } catch (Exception e) {
        	if(is != null) {
        		try {
					is.close() ;
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
        	}
            e.printStackTrace();
        }
        return result; 
    }
	
	/**
	 * word文档转pdf
	 * @param inPath
	 * @param outPath
	 */
	 public static boolean doc2pdf(String inPath, String outPath) {
		 if (!getWordLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
			 return false;
	     }
		 FileOutputStream os = null ;
		 try {
            long old = System.currentTimeMillis();
            File file = new File(outPath); // 新建一个空白pdf文档
            os = new FileOutputStream(file);
            Document doc = new Document(inPath); // Address是将要被转化的word文档
            doc.save(os, com.aspose.words.SaveFormat.PDF);// 全面支持DOC, DOCX, OOXML, RTF HTML, OpenDocument, PDF,
                                         // EPUB, XPS, SWF 相互转换
            long now = System.currentTimeMillis();
            System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒"); // 转化用时
            os.close();
		 } catch (Exception e) {
        	if(os != null) {
        		try {
					os.close();
				} catch (IOException e1) {
					e1.printStackTrace();
				}
        	}
            e.printStackTrace();
            return false ;
		 }
		 return true ;
	 }
	 
	 public static boolean getExcelLicense() {
		boolean result = false;
        InputStream is = null ;
        try {
        	is = Word2Pdf.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
        	com.aspose.cells.License aposeLic = new com.aspose.cells.License();
            aposeLic.setLicense(is);
            result = true;
            is.close();
        } catch (Exception e) {
        	if(is != null) {
        		try {
					is.close() ;
				} catch (IOException e1) {
					// TODO Auto-generated catch block
					e1.printStackTrace();
				}
        	}
            e.printStackTrace();
        }
        return result; 
	 }
	 
	 /**
	  * asponse:excel转pdf
	  * @param excelPath
	  * @param pdfPath
	  */
	 public static boolean excel2Pdf(String excelPath, String pdfPath) {
			long old = System.currentTimeMillis();
			// 验证License
			if (!getExcelLicense()) {
				return false;
			}
			FileInputStream fileInputStream = null;
			FileOutputStream fileOutputStream = null;
			try {
				File excelFile = new File(excelPath);
				if (excelFile.exists()) {
					fileInputStream = new FileInputStream(excelFile);
					Workbook workbook = new Workbook(fileInputStream);
					File pdfFile = new File(pdfPath);
					fileOutputStream = new FileOutputStream(pdfFile);
					workbook.save(fileOutputStream, com.aspose.cells.SaveFormat.PDF);
					long now = System.currentTimeMillis();
					System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒\n\n" + "文件保存在:" + pdfFile.getPath());
					return true ;
				} else {
					System.out.println("文件不存在");
					return false ;
				}
			} catch (Exception e) {
				e.printStackTrace();
				return false ;
			} finally {
				if (fileInputStream != null) {
					try {
						fileInputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
				if (fileOutputStream != null) {
					try {
						fileOutputStream.close();
					} catch (IOException e) {
						e.printStackTrace();
					}
				}
			}
	}
	 
	 
	 public static boolean getPptLicense() {
		 boolean result = false;
		 InputStream is = null ;
		 try {
			 is = Word2Pdf.class.getClassLoader().getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
			 com.aspose.slides.License aposeLic = new com.aspose.slides.License();
			 aposeLic.setLicense(is);
			 result = true;
			 is.close();
		 } catch (Exception e) {
			 if(is != null) {
				 try {
					 is.close() ;
				 } catch (IOException e1) {
					 // TODO Auto-generated catch block
					 e1.printStackTrace();
				 }
			 }
			 e.printStackTrace();
		 }
		 return result; 
	 }
	 /**
	  * aspose:ppt转pdf
	  * @param inPath
	  * @param outPath
	  */
	 public static void ppt2pdf(String inPath,String outPath) {
	    	
	    	// 验证License
			if (!getPptLicense()) {
			     return;
			}
			FileOutputStream fileOS = null ;
			try {
				long old = System.currentTimeMillis();
				File file = new File(outPath);// 输出pdf路径
				Presentation pres = new Presentation(inPath);//输入pdf路径         
				fileOS = new FileOutputStream(file);
				pres.save(fileOS, com.aspose.slides.SaveFormat.Pdf);
				fileOS.close();
			 
			    long now = System.currentTimeMillis();
			    System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒\n\n" + "文件保存在:" + file.getPath()); //转化过程耗时
			} catch (Exception e) {
				if(fileOS != null) {
					try {
						fileOS.close();
					} catch (IOException e1) {
						e1.printStackTrace();
					} 
				}
			    e.printStackTrace();
			}
	 }
	 
	 //img转pdf
		public static boolean img2PDF(String imgFilePath, String pdfFilePath){
			File file = new File(imgFilePath);
			if (file.exists()) {
				com.lowagie.text.Document document = new com.lowagie.text.Document();
				FileOutputStream fos = null;
				try {
					fos = new FileOutputStream(pdfFilePath);
					PdfWriter.getInstance(document, fos);

					// 添加PDF文档的某些信息,比如作者,主题等等
					document.addAuthor("newprint");
					document.addSubject("test pdf.");
					// 设置文档的大小
					document.setPageSize(PageSize.A4);
					// 打开文档
					document.open();
					// 写入一段文字
					// document.add(new Paragraph("JUST TEST ..."));
					// 读取一个图片
					Image image = Image.getInstance(imgFilePath);
					float imageHeight = image.getScaledHeight();
					float imageWidth = image.getScaledWidth();
					int i = 0;
					while (imageHeight > 500 || imageWidth > 500) {
						image.scalePercent(100 - i);
						i++;
						imageHeight = image.getScaledHeight();
						imageWidth = image.getScaledWidth();
						System.out.println("imageHeight->" + imageHeight);
						System.out.println("imageWidth->" + imageWidth);
					}

					image.setAlignment(Image.ALIGN_CENTER);
					// //设置图片的绝对位置
					// image.setAbsolutePosition(0, 0);
					// image.scaleAbsolute(500, 400);
					// 插入一个图片
					document.add(image);
				} catch (DocumentException de) {
					System.out.println(de.getMessage());
				} catch (IOException ioe) {
					System.out.println(ioe.getMessage());
				}
				document.close();
				try {
					fos.flush();
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			
				return true;
			} else {
				return false;
			}
		}
	 
	 
	
}

此处提供转pdf的代码,不同文件转pdf或别的格式都需要不同的jar包,下载地址:在这里插入代码片
https://download.csdn.net/download/bianqing0305/11274829
其中包含lisence.xml

版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请联系我们举报,一经查实,本站将立刻删除。

发布者:全栈程序员-站长,转载请注明出处:https://javaforall.net/136167.html原文链接:https://javaforall.net

(0)
上一篇 2022年6月4日 上午6:36
下一篇 2022年6月4日 上午6:36


相关推荐

  • GRAPESEED_radiance blue

    GRAPESEED_radiance bluehttp://www.eyemaginary.com/Portfolio/TurnColorsGray.html转载于:https://www.cnblogs.com/guochen/p/8085149.html

    2022年10月6日
    3
  • 彩色图和深度图转点云

    彩色图和深度图转点云环境:windows10、VS2013、opencv2.49、openNi、PCL1.8opencv环境搭建参考https://www.cnblogs.com/cuteshongshong/p/4057193.htmlhttps://blog.csdn.net/u013105549/article/details/50493069PCL1.8+openNi搭建参考https://blog.cs…

    2022年4月25日
    34
  • RxJava原理分析

    RxJava原理分析文章目录 RxJava 的核心思想的理解 订阅流程 1 Observer 源码 2 Observable 创建过程 3 subscribe 订阅过程 4 操作符 map 线程切换 1 subscribeOn2 observeOn 总结订阅流程线程切换 RxJava 的核心思想的理解 有一个起点和一个终点 起点开始流向我们的 事件 把事件流向终点 只不过在流的过程中可以增加拦截 对 事件 进行改变 终点只关心它的上一个流程 RxJava 的核心 订阅流程 线程切换 源码基于 io reactiv

    2026年3月19日
    2
  • 指纹和人脸识别能同时设置吗_华为畅享9有指纹吗

    指纹和人脸识别能同时设置吗_华为畅享9有指纹吗指纹识别可以说是近几年来智能手机的标配,而且也有很多机型采用了人脸识识别和指纹识别的双重解锁方案。那么华为畅享Z有指纹识别吗?支持人脸识别解锁吗。下面小编就来为大家详细解答一下,一起来看看吧!华为畅享Z有指纹识别吗?支持人脸识别解锁吗华为畅享Z有指纹识别和人脸识别解锁吗据能哈小编了解,华为畅享Z是有指纹识别功能的,不过它采用的是侧边指纹解锁,而非屏幕指纹解锁,同时它还支持人脸识别解锁方案,两者组合…

    2022年8月10日
    19
  • a标签下划线的坑

    a标签下划线的坑问题来源描述在使用Vux的tabbar组件,发现底部导航文字会有下划线,用chrome的开发者工具去找到该标签,发现就是一个span,利用各种CSS手段去删除下划线,都不起作用,但是删除这个span标签文字就消失了,span的样式里面也没有出现让其产生下划线的样式,绞尽脑汁去想各种CSS或者是JS能让span控件产生下划线的东西,一点头绪都没有。后面想想唯一的可能性就是a标签了,于是往上去找s…

    2022年5月2日
    50
  • 常用代码托管工具

    常用代码托管工具常用代码托管工具 1 Github2 Gitlab1 GithubGithub 简介由 Git 著名的 Git 版本控制软件 和 Hub 中心 的意思 两个词合成 Github 全球最大的开源项目聚集地 到目前为止 Github 汇集了全球 7300 万开发者 4000 万组织机构 2 亿代码仓库 Github 地址 https github com Github 收费模式 https www shouce ren api view a 99492 Gitlab

    2026年3月18日
    2

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注

关注全栈程序员社区公众号