public class ExcelToPDF {
private static boolean getLicense() {
boolean result = false;
try {
InputStream license = ExcelToPDF.class.getClassLoader().getResourceAsStream("\\license.xml");
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();
if (!getLicense()) {
return;
}
try {
Workbook workbook = new Workbook(inputStream);
PdfSaveOptions pdfSaveOptions = new PdfSaveOptions();
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();
}
}
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{
PDFMergerUtility mergePdf = new PDFMergerUtility();
for (File f : files) {
if(f.exists() && f.isFile()){
mergePdf.addSource(f);
}
}
mergePdf.setDestinationFileName(targetPath);
mergePdf.mergeDocuments(MemoryUsageSetting.setupMainMemoryOnly());
return new File(targetPath);
}
public static void main(String[] args) throws IOException {
excel2Pdf("/Users/hangchun.shen/Documents/sja/321.xlsx","/Users/hangchun.shen/Downloads/ToPDF11.pdf");
}
}