个人整合,java 通过aspose转PDF ,支持各种格式 JPG ,TXT, PPT, EXCEL, DOC 免费开箱即用版...


1.  导入jar包

(linux服务器转出来的PDF会有中文框框乱码,通过下载字体能解决,网上有解决办法)

itextpdf-5.5.6.jar

aspose-words-18.6-jdk16.jar

aspose.slides-15.9.0.jar

aspose-cells-8.5.2.jar

itext-asian-5.2.0.jar

链接:https://pan.baidu.com/s/1DRAnRxT037hibWey5uJ_AA 提取码:f3q1  

2.配置文件   XML

放在WEB-INF  下 classes目录下  ,配置代码:

<License>
  <Data>
    <Products>
      <Product>Aspose.Total for Java</Product>
      <Product>Aspose.Words for Java</Product>
    </Products>
    <EditionType>Enterprise</EditionType>
    <SubscriptionExpiry>20991231</SubscriptionExpiry>
    <LicenseExpiry>20991231</LicenseExpiry>
    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>
  </Data>
  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>
</License>复制代码

3.源码

开箱即用直接调:

package com.wdkj.util;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;

import com.aspose.cells.Workbook;
import com.aspose.slides.Presentation;
import com.aspose.words.Document;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Image;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;



/**
 * itext  转PDF 工具类
 * @author sunkuang
 *
 */
public class PdfUtil {
	public static File Pdf(ArrayList<String> imageUrllist,
			String mOutputPdfFileName) {
		//Document doc = new Document(PageSize.A4, 20, 20, 20, 20); // new一个pdf文档
		com.itextpdf.text.Document doc = new com.itextpdf.text.Document();
		try {
			
			PdfWriter
					.getInstance(doc, new FileOutputStream(mOutputPdfFileName)); // pdf写入
			doc.open();// 打开文档
			for (int i = 0; i < imageUrllist.size(); i++) { // 循环图片List,将图片加入到pdf中
				doc.newPage(); // 在pdf创建一页
				Image png1 = Image.getInstance(imageUrllist.get(i)); // 通过文件路径获取image
				float heigth = png1.getHeight();
				float width = png1.getWidth();
				int percent = getPercent2(heigth, width);
				png1.setAlignment(Image.MIDDLE);
				png1.scalePercent(percent + 3);// 表示是原来图像的比例;
				doc.add(png1);
			}
			doc.close();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (DocumentException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}

		File mOutputPdfFile = new File(mOutputPdfFileName); // 输出流
		if (!mOutputPdfFile.exists()) {
			mOutputPdfFile.deleteOnExit();
			return null;
		}
		return mOutputPdfFile; // 反回文件输出流
	}

	public static int getPercent(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;
	}

	public static int getPercent2(float h, float w) {
		int p = 0;
		float p2 = 0.0f;
		p2 = 530 / w * 100;
		p = Math.round(p2);
		return p;
	}
	
	
	/**
	 * 图片文件转PDF
	 * @param filepath
	 * @param request
	 * @return
	 */
	public static String imgOfPdf(String filepath, HttpServletRequest request) {
		boolean result = false;
		String pdfUrl = "";
		String fileUrl = "";
		try {
			ArrayList<String> imageUrllist = new ArrayList<String>(); // 图片list集合
			imageUrllist.add(request.getSession().getServletContext()
					.getRealPath(File.separator + filepath)); // 添加图片文件路径
			String fles = filepath.substring(0, filepath.lastIndexOf("."));
			pdfUrl = request.getSession().getServletContext()
					.getRealPath(File.separator +fles + ".pdf"); // 输出pdf文件路径
			fileUrl =fles+".pdf";
			result = true;
			if (result == true) {
				File file = PdfUtil.Pdf(imageUrllist, pdfUrl);// 生成pdf
				file.createNewFile();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
		return fileUrl;
	}
	
	

	
	/*public static void doc2pdf(String Address, String outPath) {
		if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
			return;
		}
		try {
			long old = System.currentTimeMillis();
			File file = new File(outPath); // 新建一个空白pdf文档
			FileOutputStream os = new FileOutputStream(file);
			Document doc = new Document(Address); // Address是将要被转化的word文档
			doc.save(
					os,
					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) {
			e.printStackTrace();
		}
	}*/
	
	public static boolean getLicense() {
		boolean result = false;
		try {
			
		
			
			InputStream is = PdfUtil.class.getClassLoader()
					.getResourceAsStream("license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下
			License aposeLic = new License();
			aposeLic.setLicense(is);
			result = true;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	
	public static String docOfPdf(String filePath, HttpServletRequest request) {

		if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
			return "PDF格式转化失败";
		}
		try {
			long old = System.currentTimeMillis();
			String filePath1 =  request.getSession().getServletContext().getRealPath(File.separator  + filePath);
			String filePath2 = filePath.substring(0, filePath.lastIndexOf("."));
			String pdfPathString = filePath2+".pdf";
			filePath2 = request.getSession().getServletContext()
					.getRealPath(File.separator  + filePath2 + ".pdf"); // 输出pdf文件路径
			File file = new File(filePath2); // 新建一个空白pdf文档
			FileOutputStream os = new FileOutputStream(file);
			Document doc = new Document(filePath1); // Address是将要被转化的word文档
		
			doc.save(
					os,
					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();
			
			return pdfPathString;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return "PDF格式转化失败";
	}
	
	
	public static boolean getLicense1() {
		boolean result = false;
		try {

			InputStream is = PdfUtil.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;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	

    /**
     * @param excelPath
     * @param pdfPath
     */
    public static String exceOfPdf(String filePath, HttpServletRequest request) {
        if (!getLicense1()) {          // 验证License 若不验证则转化出的pdf文档会有水印产生
        	return "PDF格式转化失败";
        }
        try {
            //long old = System.currentTimeMillis();
        	//获取路径参数
			String filePath1 =  request.getSession().getServletContext().getRealPath(File.separator + filePath);
			String filePath2 = filePath.substring(0, filePath.lastIndexOf("."));
			String pdfSPath = filePath2+".pdf";
			filePath2 = request.getSession().getServletContext()
					.getRealPath(File.separator +filePath2 + ".pdf"); // 输出pdf文件路径
			
			//文件操作
			File file = new File(filePath2); // 新建一个空白pdf文档
			FileOutputStream os = new FileOutputStream(file);
            Workbook wb = new Workbook(filePath1);// 原始excel路径
            FileOutputStream fileOS = new FileOutputStream(file);
            wb.save(fileOS, com.aspose.cells.SaveFormat.PDF);
            fileOS.close();
           // long now = System.currentTimeMillis();
            //System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");  //转化用时
            return pdfSPath;
            
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "PDF格式转化失败";
    }
    
    
	public static boolean getLicense2() {
		boolean result = false;
		try {
			
		
			
			InputStream is = PdfUtil.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;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
    
    /**
     * 
     * @param args
     */
    //public static void ppt2pdf(String Address) {
    public static String pptOfpdf(String filePath, HttpServletRequest request){
        // 验证License
        if (!getLicense2()) {
        	return "PDF格式转化失败";
        }
        try {
        	
        	
          long old = System.currentTimeMillis();
            //File file = new File("C:/Program Files (x86)/Apache Software Foundation/Tomcat 7.0/webapps/generic/web/file/pdf1.pdf");// 输出pdf路径
            //com.aspose.slides.Presentation pres = new  com.aspose.slides.Presentation(Address);//输入pdf路径       
          	String filePath1 =  request.getSession().getServletContext().getRealPath(File.separator  + filePath);
          	String filePath2 = filePath.substring(0, filePath.lastIndexOf("."));
          	String pdfPathString  = filePath2 + ".pdf";
          	filePath2 = request.getSession().getServletContext()
          			.getRealPath(File.separator  + filePath2 + ".pdf"); // 输出pdf文件路径
          	
          	 //文件操作
			File file = new File(filePath2); // 新建一个空白pdf文档
			com.aspose.slides.Presentation pres = new  com.aspose.slides.Presentation(filePath1);//输入pdf路径       
	         
            FileOutputStream 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()); //转化过程耗时
            return pdfPathString;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return "PDF格式转化失败";
    }
    
  /*  
   * 因为TXT 可以直接用上面的  DOC 方法 转    暂时 不用这个
   * public static void textOfpdf(String filePath,HttpServletRequest request) throws DocumentException, IOException {
    	
    	String text =  request.getSession().getServletContext().getRealPath("\\" + filePath);
      	String pdf = filePath.substring(0, filePath.lastIndexOf("."));
    	
    	BaseFont bfChinese = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);
    	Font FontChinese = new Font(bfChinese, 12, Font.NORMAL);
    	FileOutputStream out = new FileOutputStream(pdf);
    	Rectangle rect = new Rectangle(PageSize.A4.rotate());
    	com.itextpdf.text.Document doc = new com.itextpdf.text.Document(rect);
    	PdfWriter writer = PdfWriter.getInstance(doc, out);
    	doc.open();
    	Paragraph p = new Paragraph();
    	p.setFont(FontChinese);

    	BufferedReader read = new BufferedReader(new FileReader(text));

    	String line = read.readLine();
    	while(line != null){
    	System.out.println(line);
    	p.add(line+"\n");
    	line = read.readLine();
    	}
    	read.close();
    	doc.add(p);
    	doc.close();
   
    }*/
}复制代码




转载于:https://juejin.im/post/5ce36b05e51d4555fe1777d6

  • 3
    点赞
  • 12
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值