引入Jar包可参考本文章
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 =
"<License>\n" +
"<Data>\n" +
" <Products>\n" +
" <Product>Aspose.Total for Java</Product>\n" +
" <Product>Aspose.Excel for Java</Product>\n" +
" </Products>\n" +
" <EditionType>Enterprise</EditionType>\n" +
" <SubscriptionExpiry>20991231</SubscriptionExpiry>\n" +
" <LicenseExpiry>20991231</LicenseExpiry>\n" +
" <SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber>\n" +
"</Data>\n" +
"<Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature>\n" +
"</License>";
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) {
if (!getLicense()) {
return null;
}
try {
Workbook wb = new Workbook(inputStream);
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
pdfSaveOptions.setOnePagePerSheet(false);
int[] autoDrawSheets={3};
autoDraw(wb,autoDrawSheets);
int[] showSheets={0};
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);
}
}
}
}