引入Jar包可参考本文章
//需要先转换成InputStream 返回的是byte InputStream inputStream = FileUtils.workbookToInputStream(workbook); ByteArrayOutputStream stream = new ByteArrayOutputStream(); byte[] bytes = PdfConverUtil.workbookToPdf(inputStream, stream);
package com.diye.gw.hotelapisystem.util;
import com.aspose.cells.License;
import com.aspose.cells.PdfSaveOptions;
import com.aspose.cells.Workbook;
import lombok.extern.log4j.Log4j2;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
@Log4j2
public class PdfConverUtil {
private static boolean getLicense() {
boolean result = false;
try {
// 凭证
String licenseStr =
"n" +
"n" +
" n" +
" Aspose.Total for Java n" +
" Aspose.Excel for Java n" +
" n" +
" Enterprise n" +
" 20991231 n" +
" 20991231 n" +
" 8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7 n" +
"n" +
"sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU= n" +
" ";
InputStream license = new ByteArrayInputStream(licenseStr.getBytes("UTF-8"));
License asposeLic = new License();
asposeLic.setLicense(license);
result = true;
} catch (Exception e) {
log.error("error:", e);
}
return result;
}
public static byte[] workbookToPdf(InputStream inputStream, ByteArrayOutputStream stream) {
// 验证License 若不验证则转化出的pdf文档会有水印产生
if (!getLicense()) {
return null;
}
try {
Workbook wb = new Workbook(inputStream);// 原始excel路径
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.setOnePagePerSheet(false);
int[] autoDrawSheets={3};
//当excel中对应的sheet页宽度太大时,在PDF中会拆断并分页。此处等比缩放。
autoDraw(wb,autoDrawSheets);
int[] showSheets={0};
//隐藏workbook中不需要的sheet页。
printSheetPage(wb,showSheets);
wb.save(stream, pdfSaveOptions);
byte[] bytes = null;
bytes = stream.toByteArray();
System.out.println("pdf转换完毕......");
return bytes;
} catch (IOException e) {
e.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
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();
}
}
}
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);
}
}
}
}



