1. 程式人生 > 其它 >java將excel轉成pdf

java將excel轉成pdf

分享一個簡單的excel轉pdf

1、引用aspose-cells工具

<dependency>
    <groupId>com.zy</groupId>
    <artifactId>aspose-cells</artifactId>
    <version>17.8.0</version>
</dependency>

2、由於轉換後會產生水印,去除PDF水印,需要進行許可權認證,許可權認證檔案是license.xml,已經放在網盤

連結:https://pan.baidu.com/s/1wgdQD1UfYmJLf5iES5la7Q
提取碼:kj64

3、話不多說,上程式碼

package com.zy.jeerdp.modules.ar.utils;

import com.aspose.cells.License;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import com.zy.jeerdp.common.utils.IdGen;

import java.io.*;


public class Excel2PdfUtil {
    /**
     * excel檔案轉換為PDF檔案
     * @param Address 需要轉化的Excel檔案地址,
     * 
@param outputPath 轉換後的檔案地址 */ public static String excel2pdf(String Address,String outputPath) { String fileName = IdGen.uuid() + ".pdf"; if (!getLicense()) { // 驗證License 若不驗證則轉化出的pdf文件會有水印產生 return null; } try { FileWriter writer = new
FileWriter(outputPath + fileName); writer.close(); File pdfFile = new File(outputPath + fileName); // 輸出路徑 FileInputStream excelstream = new FileInputStream(Address); Workbook wb = new Workbook(excelstream);// excel路徑,這裡是先把資料放進快取表裡,然後把快取錶轉化成PDF FileOutputStream fileOS = new FileOutputStream(pdfFile); PdfSaveOptions pdfSaveOptions = new PdfSaveOptions(); pdfSaveOptions.setOnePagePerSheet(true);//引數true把內容放在一張PDF頁面上; wb.save(fileOS, pdfSaveOptions); fileOS.close(); } catch (Exception e) { e.printStackTrace(); } return fileName; } //獲取認證,去除水印 public static boolean getLicense() { boolean result = false; try { InputStream is = Excel2PdfUtil.class.getClassLoader().getResourceAsStream("pdfLicense/license.xml");//這個檔案應該是類似於密碼驗證(證書?),用於獲得去除水印的許可權 License aposeLic = new License(); aposeLic.setLicense(is); result = true; } catch (Exception e) { e.printStackTrace(); } return result; } }