<!-- https://mvnrepository.com/artifact/org.apache.pdfbox/pdfbox -->
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.24</version>
</dependency>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-cells</artifactId>
<version>8.5.2</version>
</dependency>
public class ExcelToPdf {
private static License asposeLic;
public static void main(String[] args) throws IOException {
//convertPDFImage("d:\demo.xls", null);
// 直接在相同目录输出pdf文件
ExcelToPdf.convertPDF("D:\\kfcode\\file-online-preview-v4.0.0\\server\\src\\main\\file\\888.xlsx");
}
public static String convertPDF(String excelFileName) {
return convertPDF(false, excelFileName);
}
/**
* 是否每页大小自适应(超页不分页)
*
* @param onePagePerSheet excel每sheet页生成一页pad
* @param excelFileName excel 文件
* @return pdf
*/
public static String convertPDF(boolean onePagePerSheet, String excelFileName) {
String pdfFileName = "";
PDDocument pdfDocument = null;
try {
Workbook workbook = new Workbook(excelFileName);
getLicense();
PdfSaveOptions saveOptions = new PdfSaveOptions();
saveOptions.setCompliance(PdfCompliance.PDF_A_1_B);
saveOptions.setOnePagePerSheet(onePagePerSheet);
saveOptions.setAllColumnsInOnePagePerSheet(true);
pdfFileName = excelFileName.substring(0, excelFileName.lastIndexOf(".")) + ".pdf";
workbook.save(pdfFileName, saveOptions);
pdfDocument = PDDocument.load(new File(pdfFileName));
// Output file name
pdfDocument.save(pdfFileName);
//editPDF(pdfFileName);
} catch (Exception e) {
e.printStackTrace();
}finally {
if (pdfDocument != null) {
try {
pdfDocument.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
return pdfFileName;
}
/**
* 获取license
*
* @return
*/
public static boolean getLicense() {
boolean result = false;
InputStream license = null;
try {
license = ExcelToPdf.class.getClassLoader().getResourceAsStream("/license.xml");
asposeLic = new License();
asposeLic.setLicense(license);
result = true;
} catch (Exception e) {
e.printStackTrace();
} finally {
try {
if (license != null) {
license.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
return result;
}
public static boolean delete(String strFileName) {
File fileDelete = new File(strFileName);
if (!fileDelete.exists() || !fileDelete.isFile()) {
System.out.println("错误: " + strFileName + "不存在!");
return false;
}
return fileDelete.delete();
}
}