使用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)
全栈程序员-站长的头像全栈程序员-站长


相关推荐

  • 第一个C# Winform实例

    第一个C# Winform实例前面我们准备好了相关的库,现在开始搭建环境,本人自动化行业,就用Windorm开发吧,例子仅仅做引导,希望大家能深入。VS版本VS20171:打开VS建立一个WInform项目。拉入两个控件,gr

    2022年7月2日
    31
  • dhcp option 82 接入交换机_dhcpoption怎么配置

    dhcp option 82 接入交换机_dhcpoption怎么配置Option82应用场景在该场景下,临时接入者可以在不安装认证客户端的情况下,直接访问Internet资源,但是不能访问学校、企业、政府单位的内网,适用于各种会务、学术交流、临时参观等应用场景,正式员工可以在会议区通过认证接入到内网。为了实现该场景,我们首先要对神州数码网络交换机产品的DHCPOption82功能进行描述。Option82相关技术Option82功能介绍  DH…

    2022年10月16日
    4
  • 单片机(AT89C51)的串行通信实验

    单片机(AT89C51)的串行通信实验串口通信的重要性和基础就不用我多讲了吧 基础不懂直接点链接 https blog csdn net weixin article details 这一次的重点是讲解几个串口的实验来加深自己对串口通信的理解 实验一 将一个简单的字符串输出到单片机中 实验目的 实现输出 nihao 用 VIRTUALTERMI 显示出来

    2025年7月1日
    6
  • 【NVIDIA】Win10 + CUDA10 + cuDNN 安装教程

    【NVIDIA】Win10 + CUDA10 + cuDNN 安装教程目录一、前言二、官方安装教程及软件包1、官方教程2、CUDAToolkit10.0Download3、cuDNNDownload三、Win10安装CUDA10及cuDNN1、CUDA安装2、cuDNN配置3、万事大吉,只欠重启四、一些后事问题1:安装过程中电脑自动重启。问题2:安装完成后找不到CUDA文件夹。一、前言其实听早就接触NV…

    2022年6月10日
    46
  • C++并发实战19:lock free编程

    C++并发实战19:lock free编程涉及到并行/并发计算时,通常都会想到加锁,加锁可以保护共享的数据,不过也会存在一些问题:1.由于临界区无法并发运行,进入临界区就需要等待,加锁使得效率的降低。多核CPU也不能发挥全部马力2.在复杂的情况下,很容易造成死锁,并发进程、线程之间无止境的互相等待。3.在中断/信号处理函数中不能加锁,给并发处理带来困难。4.加锁影响实时性,等待时间不确定5.优先级反转,优先级

    2022年7月19日
    21
  • DeepLab v3_deeplab模型导出

    DeepLab v3_deeplab模型导出大年初一我居然在更博客。今年过年由于病毒横行,没有串门没有聚餐,整个人闲的没事干。。。医生真是不容易,忙得团团转还有生命危险,新希望他们平安。本篇不属于初级教程。如果完全看不懂请自行谷歌或搜索作者博客。deeplab官方提供了多种backbone,通过train.py中传递参数,–model_variant=”resnet_v1_101_beta”\可以更改backbone。…

    2022年9月25日
    5

发表回复

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

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