我的整合,java 經過aspose轉PDF ,支持各類格式 JPG ,TXT, PPT, EXCEL, DOC 免費開箱即用版


1.  導入jar包

(linux服務器轉出來的PDF會有中文框框亂碼,經過下載字體能解決,網上有解決辦法)
java

itextpdf-5.5.6.jar
linux

aspose-words-18.6-jdk16.jar
web

aspose.slides-15.9.0.jar
服務器

aspose-cells-8.5.2.jar
app

itext-asian-5.2.0.jar
webapp

連接:https://pan.baidu.com/s/1DRAnRxT037hibWey5uJ_AA 提取碼:f3q1  
ide

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(); }*/
}複製代碼
相關文章
相關標籤/搜索