Java doc或docx转pdf文件预览
1.获取doc或docx文件路径,判断文件是否存在,然后新生成一个pdf文件。
2.写入文件流,转成pdf文件。
注:需要添加一个maven依赖,aspose-words-15.8.0-jdk16.jar包
该jar包没有的可以去我主页下载
代码如下
public Map<String, Object> getFileStream(HttpServletResponse response,String fileName) {
File pdfFile = null;
OutputStream outputStream = null;
BufferedInputStream bufferedInputStream = null;
// String docPath = fileName + ".doc";
// String pdfPath = fileName + ".pdf";
try {
//获取生成的pdf
pdfFile = FileUtil.getFileStream(fileName);
outputStream = response.getOutputStream();
response.setContentType("application/pdf;charset=UTF-8");
bufferedInputStream = new BufferedInputStream(new FileInputStream(pdfFile));
byte buffBytes[] = new byte[1024];
outputStream = response.getOutputStream();
int read = 0;
//docx||doc文档流写入pdf文件
while ((read = bufferedInputStream.read(buffBytes)) != -1) {
outputStream.write(buffBytes, 0, read);
}
} catch (ConnectException e) {
//logger.info("****调用Doc2PdfUtil doc转pdf失败****");
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
if(outputStream != null){
try {
outputStream.flush();
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
if(bufferedInputStream != null){
try {
bufferedInputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return null;
}
FileUtil类
public static File getFileStream(String fileName) {
//获取项目路径
File path4 = new File(new File(new File(new File(path).getParent()).getParent()).getParent());
//文件路径
String docPath = path4.getPath()+fileName;
//String docPath = "D://" + fileName;
if (!new File(docPath).exists()) {
return null;
}
String str[] = docPath.split("[.]");
if (str[str.length-1]=="pdf"){
return new File(docPath);
}
String pdfName = docPath.replace(str[str.length-1],"pdf");
System.out.println(pdfName);
File pdfFile = new File(pdfName);
try {
String s = "<License><Data><Products><Product>Aspose.Total for Java</Product><Product>Aspose.Words for Java</Product></Products><EditionType>Enterprise</EditionType><SubscriptionExpiry>20991231</SubscriptionExpiry><LicenseExpiry>20991231</LicenseExpiry><SerialNumber>8bfe198c-7f0c-4ef8-8ff0-acc3237bf0d7</SerialNumber></Data><Signature>sNLLKGMUdF0r8O1kKilWAGdgfs2BvJb/2Xp8p5iuDVfZXmhppo+d0Ran1P9TKdjV4ABwAgKXxJ3jcQTqE/2IRfqwnPf8itN8aFZlV3TJPYeD3yWE7IT55Gz6EijUpC7aKeoohTb4w2fpox58wWoF3SNp6sK6jDfiAUGEHYJ9pjU=</Signature></License>";
ByteArrayInputStream is = new ByteArrayInputStream(s.getBytes());
License license = new License();
license.setLicense(is);
Document document = new Document(docPath);
document.save(new FileOutputStream(pdfFile),SaveFormat.PDF);
} catch (Exception e) {
//logger.info("****aspose doc转pdf异常");
e.printStackTrace();
}
if (!pdfFile.exists()) {
return null;
}
return pdfFile;
}
pom.xml
maven仓库没有的话需要本地jar包发布到私服
这样正常不出错的情况下就可以通过docx或doc文件,来预览pdf文件了。
执行结果如下
代码执行前
代码执行后
它会生成一个文件名相同的pdf文件,不需要pdf文件的话可以写一个预览完成后删除掉pdf文件方法来减少资源在内存中的占用。