java excel转pdf

本文介绍了如何在项目中使用Aspose Java API库将Excel转换为PDF,包括添加依赖、获取去除水印的许可证,并展示了关键的代码片段。特别提到了在Linux环境下可能遇到的字体问题和解决方案。
摘要由CSDN通过智能技术生成

需要的依赖和仓库地址

		<repository>
            <id>AsposeJavaAPI</id>
            <name>Aspose Java API</name>
            <url>https://repository.aspose.com/repo/</url>
        </repository>

		 <dependency>
		     <groupId>com.aspose</groupId>
		     <artifactId>aspose-cells</artifactId>
		     <version>21.8</version>
		 </dependency>
		<dependency>
		     <groupId>org.javassist</groupId>
		     <artifactId>javassist</artifactId>
		     <version>3.20.0-GA</version>
		 </dependency>	

Tips:

jar包如果无法下载,可以从百度云下载

链接:https://pan.baidu.com/s/1He4YPMjFHezVd0-L0csm5g?pwd=e2pt 
提取码:e2pt

 

工具类


import java.io.ByteArrayInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;

import com.aspose.cells.IndividualFontConfigs;
import com.aspose.cells.License;
import com.aspose.cells.LoadOptions;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;

/**
* excel转pdf
* @description:xlsx转pdf
*/
public class ExcelToPdf {
	public static void main(String[] args) {
		excel2pdf("C:\\Users\\admin\\Desktop\\1.xlsx","E:\\a\\excel转pdf\\3.pdf");
	}
   /**
    * 获取license 去除水印
    * @return
    */
   public static boolean getLicense() {
       boolean result = false;
       try {
    	   String license = "<License>\r\n" + 
    	   		"  <Data>\r\n" + 
    	   		"    <Products>\r\n" + 
    	   		"      <Product>Aspose.Total for Java</Product>\r\n" + 
    	   		"      <Product>Aspose.Words for Java</Product>\r\n" + 
    	   		"    </Products>\r\n" + 
    	   		"    <EditionType>Enterprise</EditionType>\r\n" + 
    	   		"    <SubscriptionExpiry>20991231</SubscriptionExpiry>\r\n" + 
    	   		"    <LicenseExpiry>20991231</LicenseExpiry>\r\n" + 
    	   		"    <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\r\n" + 
    	   		"  </Data>\r\n" + 
    	   		"  <Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\r\n" + 
    	   		"</License>";
    	   
           InputStream is = new  ByteArrayInputStream(license.getBytes("UTF-8"));
           License aposeLic = new License();
           aposeLic.setLicense(is);
           result = true;
       } catch (Exception e) {
           e.printStackTrace();
       }
       return result;
   }

   /**
    * excel 转为pdf 输出。
    *
    * @param sourceFilePath  excel文件
    * @param desFilePathd  pad 输出文件目录
    */
   public static void excel2pdf(String sourceFilePath, String desFilePathd){
       if (!getLicense()) { // 验证License 若不验证则转化出的pdf文档会有水印产生
           return;
       }
       try {
    	   if(isLinux()) {
    		   IndividualFontConfigs configs = new IndividualFontConfigs();
    		   configs.setFontFolder("/usr/share/fonts/chinese", true);
    		   LoadOptions loadOptions  = new LoadOptions();
             	loadOptions.setFontConfigs(configs);
    	   }

    
           
           Workbook wb = new Workbook(sourceFilePath);// 原始excel路径

           FileOutputStream fileOS = new FileOutputStream(desFilePathd);
           PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
           pdfSaveOptions.setOnePagePerSheet(true);
           int[] autoDrawSheets={3};
           //当excel中对应的sheet页宽度太大时,在PDF中会拆断并分页。此处等比缩放。
           autoDraw(wb,autoDrawSheets);
           int[] showSheets={0};
           //隐藏workbook中不需要的sheet页。
           printSheetPage(wb,showSheets);
           wb.save(fileOS, pdfSaveOptions);
           fileOS.flush();
           fileOS.close();
           //System.out.println("转换PDF完毕!");
       } catch (Exception e) {
           e.printStackTrace();
       }
   }

   /**
    * 设置打印的sheet 自动拉伸比例
    * @param wb
    * @param page 自动拉伸的页的sheet数组
    */
   public static void autoDraw(Workbook wb,int[] page){
       if(null!=page&&page.length>0){
           for (int i = 0; i < page.length; i++) {
               wb.getWorksheets().get(i).getHorizontalPageBreaks().clear();
               wb.getWorksheets().get(i).getVerticalPageBreaks().clear();
           }
       }
   }


   /**
    * 隐藏workbook中不需要的sheet页。
    * @param wb
    * @param page 显示页的sheet数组
    */
   public static void printSheetPage(Workbook wb,int[] page){
       for (int i= 1; i < wb.getWorksheets().getCount(); i++)  {
           wb.getWorksheets().get(i).setVisible(false);
       }
       if(null==page||page.length==0){
           wb.getWorksheets().get(0).setVisible(true);
       }else{
           for (int i = 0; i < page.length; i++) {
               wb.getWorksheets().get(i).setVisible(true);
           }
       }
   }
   
   
   public static boolean isLinux() {
       return System.getProperty("os.name").toLowerCase().contains("linux");
   }

   public static boolean isWindows() {
       return System.getProperty("os.name").toLowerCase().contains("windows");
   }

   public String JudgeSystem() {
       if (isLinux()) {
           return "linux";
       } else if (isWindows()) {
           return "windows";
       } else {
           return "other system";
       }
   }
}

controller测试类

	@PostMapping("/excel2pdf")
	public String excel2pdf(MultipartFile file ) throws IllegalStateException, IOException{
		String fileName = file.getOriginalFilename();

		String localFilePath = StrUtil.appendIfMissing("/data/apps/bms/test", "/") + fileName;
		
		
		file.transferTo(new File(localFilePath));
		ExcelToPdf.excel2pdf(localFilePath, "/data/apps/bms/test/" + fileName.split("\\.")[0] + ".pdf");

		return "success可喜可贺";
	}

备注:

在linux上转换的时候会有乱码问题,需要在指定位置(如代码所示:/usr/local/fonts/chinese)放windows的字体包C:\Windows\Fonts

Java中,将Excel文件换成PDF通常需要使用一些库来处理电子表格和生成PDF文档。Apache POI是一个常用的Java库,用于操作Microsoft Office格式(包括Excel),而iText或Flying Saucer等库则可以用来创建PDF文件。 以下是一个简单的步骤示例: 1. 引入所需的库依赖: - poi:`<dependency> <groupId>org.apache.poi</groupId> <artifactId>poi</artifactId> <version>最新版本</version> </dependency>` - iText或itextpdf:`<dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>最新版本</version> </dependency>` 2. 使用POI读取Excel数据: ```java FileInputStream fis = new FileInputStream("input.xlsx"); HSSFWorkbook workbook = new HSSFWorkbook(fis); Sheet sheet = workbook.getSheetAt(0); // 获取第一个工作表 ``` 3. 将数据换为iText元素(如果使用iText): ```java PdfDocument pdfDoc = new PdfDocument(); for (Row row : sheet) { List<Cell> cells = row.Cells; for (Cell cell : cells) { String cellValue = cell.getStringCellValue(); // 添加到PDF的相应位置 } } ``` 4. 创建并写入PDF: ```java PdfPTable table = new PdfPTable(numberOfColumns); for (Row row : sheet) { PdfPCell cell = createTableCell(row); table.addCell(cell); } pdfDoc.add(table); try (OutputStream os = new FileOutputStream("output.pdf")) { pdfDoc.write(os); } ``` 5. 关闭资源: ```java workbook.close(); pdfDoc.close(); fis.close(); ``` 注意:这个过程可能会比较复杂,特别是处理表格样式和合并单元格等问题,实际操作时可能需要根据具体需求调整。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值