execl、word转pdf

本文介绍如何使用Aspose库将Excel和Word文档转换为PDF格式。包括必要的jar包和示例代码,演示了如何设置License以避免生成的PDF带有水印。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Execl转PDF

1.需要的jar包

aspose-cells-8.5.2.jar

2.代码

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.UUID;

import com.aspose.cells.License;
import com.aspose.cells.SaveFormat;
import com.aspose.cells.Workbook;

public class Excel2PDF {
	public static boolean hasUsablelicense() {
		boolean result = false;
		InputStream is = Excel2Pdf.class.getClassLoader().getResourceAsStream(
				"license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下(即编程时放在src下)
		License aposeLic = new License();
		aposeLic.setLicense(is);
		result = true;
		return result;
	}

	public static String excel2pdf(String execlPath) throws Exception {
		FileOutputStream fileOS = null;
		if (hasUsablelicense()) { // 验证License, 若不验证则转化出的pdf文档会有水印
			try {
				String filePath = UtilFuns.getROOTPath()+File.separator+"temp"+File.separator+UUID.randomUUID().toString()+".pdf";
				File pdfFile = new File(filePath);// pdf文件输出路径
				if (!pdfFile.exists()) {
					pdfFile.createNewFile();
				}
				Workbook wb = new Workbook(execlPath);// excel文件路径(注意这里不是POI的Workbook)
				fileOS = new FileOutputStream(pdfFile);
				wb.save(fileOS, SaveFormat.PDF);
				return filePath;
			} finally {
				if(fileOS!=null){
					fileOS.close();
				}
			}
		}else{
			return null;
		}
	}
}

Word转PDF

1.导入jar包

aspose-words-16.8.0-jdk16.jar

2.代码

import java.io.*;
import com.aspose.words.*; 

public class Word2PDF {
	public static boolean hasUsablelicense() throws Exception {
		boolean result = false;
		InputStream is = Word2Pdf.class.getClassLoader().getResourceAsStream(
				"licenseWord.xml"); // licenseWord.xml应该放在classes路径下
		License aposeLic = new License();
		aposeLic.setLicense(is);
		result = true;
		return result;
	}

	public static String word2pdf(String wordPath) throws Exception {
		if (hasUsablelicense()) { // 验证License,若不验证则转化出的PDP文档会有水印产生
			String pdfFilePath = "d:/test.pdf";
			File pdfFile = new File(pdfFilePath);
			FileOutputStream os = null;
			try {
				if (!pdfFile.exists()) {
					pdfFile.createNewFile();
				}
				os = new FileOutputStream(pdfFile);
				Document doc = new Document(wordPath);
				doc.save(os, SaveFormat.PDF); 
			} finally {
				if (os != null) {
					os.close();
				}
			}

			return pdfFilePath;
		} else {
			return null;
		}

	}
	public static void main(String[] args) throws Exception {
		Word2PDF.word2pdf("D:\\Downloads\\帮助文档.docx");
	}
}







评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值