最近项目需要转换office文件为pdf,踩过很多坑,希望可以帮助中后来的人吧
import com.aspose.cells.Worksheet;
import com.aspose.words.License;
import com.aspose.words.SaveFormat;
/**
* 去除Aspose水印
* @return
*/
public static boolean getLicense() {
boolean result = true;
try {
InputStream license = Change2PDF.class.getClassLoader().getResourceAsStream("license.xml"); // license路径
License aposeLic = new License();
aposeLic.setLicense(license);
} catch (Exception e) {
result=false;
}
return result;
}
/**
* doc转换pdf(doc,docx)
* @param filePath
* @param pdfPath
*/
public static boolean doc2PDF(String filePath, String pdfPath) {
boolean bool=true;
FileOutputStream os = null;
try {
if(!getLicense()){
System.out.println("授权失效,请联系管理员");
bool=false;
return bool;
}
File file = new File(pdfPath);
os = new FileOutputStream(file);
com.aspose.words.Document doc = new com.aspose.words.Document(filePath);
doc.save(os, SaveFormat.PDF);
} catch (Exception e) {
e.printStackTrace();
bool=false;
} finally {
if (os != null) {
try {
os.close();
} catch (IOException e) {
e.printStackTrace();
bool=false;
}
}
return bool;
}
}
/**
* excel转换pdf(xls,xlsx)
* @param excelPath
* @param pdfPath
* @return
* @throws Exception
*/
public static boolean excel2PDF(String excelPath,String pdfPath) throws Exception {
boolean bool=true;
if (getLicense()) {
InputStream inputStream = new FileInputStream(new File(excelPath));
OutputStream outputStream = new FileOutputStream(new File(pdfPath));
com.aspose.cells.Workbook workbook = new com.aspose.cells.Workbook(inputStream);
Worksheet ws = workbook.getWorksheets().get(0);
com.aspose.cells.PdfSaveOptions pdfSaveOptions = new com.aspose.cells.PdfSaveOptions();
pdfSaveOptions.setOnePagePerSheet(true);
ws.getHorizontalPageBreaks().clear();
ws.getVerticalPageBreaks().clear();
workbook.save(outputStream, pdfSaveOptions);
outputStream.flush();
outputStream.close();
// TODO 当excel宽度太大时,在PDF中会拆断并分页。此处如何等比缩放。
// 将不同的sheet单独保存为pdf
//Get the count of the worksheets in the workbook
// int sheetCount = workbook.getWorksheets().getCount();
System.out.println("excel to pdf success");
return bool;
} else {
System.out.println("excel to pdf error");
bool=false;
return bool;
}
}
<!--Aspose密匙 Excel没法去水印word完美 xml文件放在resources目录下-->
<License>
<Data>
<Products>
<Product>Aspose.Words for Java</Product>
</Products>
<EditionType>Enterprise</EditionType>
<SubscriptionExpiry>29991231</SubscriptionExpiry>
<LicenseExpiry>29991231</LicenseExpiry>
<SerialNumber>---</SerialNumber>
</Data>
<Signature>---</Signature>
</License>