Execl转PDF
1.需要的jar包
aspose-cells-8.5.2.jar
2.代码
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.UUID;
import com.aspose.cells.License;
import com.aspose.cells.SaveFormat;
import com.aspose.cells.Workbook;
public class Excel2PDF {
public static boolean hasUsablelicense() {
boolean result = false;
InputStream is = Excel2Pdf.class.getClassLoader().getResourceAsStream(
"license.xml"); // license.xml应放在..\WebRoot\WEB-INF\classes路径下(即编程时放在src下)
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
return result;
}
public static String excel2pdf(String execlPath) throws Exception {
FileOutputStream fileOS = null;
if (hasUsablelicense()) { // 验证License, 若不验证则转化出的pdf文档会有水印
try {
String filePath = UtilFuns.getROOTPath()+File.separator+"temp"+File.separator+UUID.randomUUID().toString()+".pdf";
File pdfFile = new File(filePath);// pdf文件输出路径
if (!pdfFile.exists()) {
pdfFile.createNewFile();
}
Workbook wb = new Workbook(execlPath);// excel文件路径(注意这里不是POI的Workbook)
fileOS = new FileOutputStream(pdfFile);
wb.save(fileOS, SaveFormat.PDF);
return filePath;
} finally {
if(fileOS!=null){
fileOS.close();
}
}
}else{
return null;
}
}
}
Word转PDF
1.导入jar包
aspose-words-16.8.0-jdk16.jar
2.代码
import java.io.*;
import com.aspose.words.*;
public class Word2PDF {
public static boolean hasUsablelicense() throws Exception {
boolean result = false;
InputStream is = Word2Pdf.class.getClassLoader().getResourceAsStream(
"licenseWord.xml"); // licenseWord.xml应该放在classes路径下
License aposeLic = new License();
aposeLic.setLicense(is);
result = true;
return result;
}
public static String word2pdf(String wordPath) throws Exception {
if (hasUsablelicense()) { // 验证License,若不验证则转化出的PDP文档会有水印产生
String pdfFilePath = "d:/test.pdf";
File pdfFile = new File(pdfFilePath);
FileOutputStream os = null;
try {
if (!pdfFile.exists()) {
pdfFile.createNewFile();
}
os = new FileOutputStream(pdfFile);
Document doc = new Document(wordPath);
doc.save(os, SaveFormat.PDF);
} finally {
if (os != null) {
os.close();
}
}
return pdfFilePath;
} else {
return null;
}
}
public static void main(String[] args) throws Exception {
Word2PDF.word2pdf("D:\\Downloads\\帮助文档.docx");
}
}