public class ExcelToPDF {
/**
* 获取license
*
* @return
*/
private static boolean getLicense() {
boolean result = false;
try {
InputStream license = ExcelToPDF.class.getClassLoader().getResourceAsStream("\\license.xml");// license路径
License aposeLic = new License();
aposeLic.setLicense(license);
result = true;
} catch (Exception e) {
e.printStackTrace();
}
return result;
}
public static void excel2Pdf(InputStream inputStream, OutputStream outputStream){
long old = System.currentTimeMillis();
// 验证License
if (!getLicense()) {
return;
}
try {
Workbook workbook = new Workbook(inputStream);
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
//把内容放在一张PDF 页面上;
pdfSaveOptions.setOnePagePerSheet(false);
pdfSaveOptions.setAllColumnsInOnePagePerSheet(true);
pdfSaveOptions.setFontSubstitutionCharGranularity(true);
// 只放一张纸;我的专为横向了
workbook.save(outputStream, pdfSaveOptions);
long now = System.currentTimeMillis();
System.out.println("共耗时:" + ((now - old) / 1000.0) + "秒");
} catch (Exception e) {
e.printStackTrace();
}
}
/**
*
* @param excelPath 文件路径
* @param outputStream
*/
public static void excel2Pdf(String excelPath, OutputStream outputStream) {
FileInputStream fileInputStream = null;
try {
File excelFile = new File(excelPath);
if (excelFile.exists()) {
fileInputStream = new FileInputStream(excelFile);
excel2Pdf(fileInputStream,outputStream);
}else{
System.out.println("文件不存在");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (fileInputStream != null) {
try {
fileInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static void excel2Pdf(String excelPath, String pdfPath) {
File pdfFile = new File(pdfPath);
FileOutputStream fileOS = null;
try {
fileOS = new FileOutputStream(pdfFile);
excel2Pdf(excelPath,fileOS);
} catch (FileNotFoundException e) {
e.printStackTrace();
}finally {
if (fileOS != null) {
try {
fileOS.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
public static File mulFile2One(List<File> files, String targetPath) throws IOException{
// pdf合并工具类
PDFMergerUtility mergePdf = new PDFMergerUtility();
for (File f : files) {
if(f.exists() && f.isFile()){
// 循环添加要合并的pdf
mergePdf.addSource(f);
}
}
// 设置合并生成pdf文件名称
mergePdf.setDestinationFileName(targetPath);
// 合并pdf
mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
return new File(targetPath);
}
/**
* @param args
*/
public static void main(String[] args) throws IOException {
excel2Pdf("/Users/hangchun.shen/Documents/sja/321.xlsx","/Users/hangchun.shen/Downloads/ToPDF11.pdf");
// excel2Pdf("/Users/hangchun.shen/Documents/sja/456.xlsx","/Users/hangchun.shen/Downloads/ToPDF9.pdf");
// List<File> files = new ArrayList <>();
//
// File a = new File("/Users/hangchun.shen/Downloads/ToPDF8.pdf");
// File b = new File("/Users/hangchun.shen/Downloads/ToPDF9.pdf");
// files.add(b);
// files.add(a);
// mulFile2One(files,"/Users/hangchun.shen/Downloads/ToPDF10.pdf");
}
}
Excel转PDF工具类
最新推荐文章于 2024-06-19 16:38:13 发布