一般情况,pdf类型的文件在前端预览,都是通过前端插件,或者获取源文件浏览器自带的工具预览,由于项目中,是前后端分离,前端不想使用pdf.js类的插件,预览的要求又是只能看不能下载,所以只能另外想别的办法处理,参照之前openoffice将word/excel能转换成html的功能思路,想到能否将pdf也转换成html进行预览
于是就找到了apache的一个pdfbox的工具包能将pdf转换成图片,于是想到一个实现方案
1.将pdf转换成图片,图片保存在文件服务器,能通过get请求和图片地址获取
2.拼接一段html文件的代码,将每一个图片作为img标签的src插入html代码中
3.最后将这段html代码生成一个html文件,预览时,直接获取这个html就能查看
1.引入包
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox</artifactId>
<version>2.0.19</version>
</dependency>
<dependency>
<groupId>org.apache.pdfbox</groupId>
<artifactId>pdfbox-tools</artifactId>
<version>2.0.19</version>
</dependency>
2.转换代码和生成图片代码以及拼接html生成文件代码
public static String pdf2Html(File file, String savePath, String saveUrl) throws Exception {
String htmlFileName = UUID.randomUUID().toString().replace("-", "") + ".html";
String htmlPath = DateUtils.formateDate(new Date(), "yyyy/MM/dd");
String htmlFilePath = "D:/" + htmlFileName;
PDDocument pdf = PDDocument.load(file, (String) null);
//pdf每页转换成一张png图片
StringBuffer buffer= saveImage(pdf,getHtml(), saveUrl);
pdf.close();
buffer.append("</body>\r\n");
buffer.append("</html>");
//生成网页文件
String htmlFile = saveUrl + htmlFilePath;
File html = new File(htmlFile);
if (!html.exists()) {
html.createNewFile();
}
FileOutputStream fos = new FileOutputStream(htmlFile);
fos.write(buffer.toString().getBytes());
fos.flush();
fos.close();
buffer.setLength(0)
return new htmlFilePath;
}
private static StringBuffer getHtml() {
StringBuffer buffer = new StringBuffer();
buffer.append("<!doctype html>\r\n");
buffer.append("<head>\r\n");
buffer.append("<meta charset=\"UTF-8\">\r\n");
buffer.append("</head>\r\n");
buffer.append("<body style=\"background-color:gray;\">\r\n");
buffer.append("<style>\r\n");
buffer.append("img {background-color:#fff; text-align:center; width:100%; max-width:100%;margin-top:6px;}\r\n");
buffer.append("</style>\r\n");
return buffer;
}
private static StringBuffer saveImage(PDDocument pdf, StringBuffer buffer, String saveUrl) throws Exception {
String path = DateUtils.formateDate(new Date(), "yyyy/MM/dd");
String imageDir = "D:/" + path + "/images";
PDFRenderer reader = new PDFRenderer(pdf);
int size = pdf.getNumberOfPages();
for (int i = 0; i < size; i++) {
String imageName = UUID.randomUUID().toString().replace("-", "") + ".jpg";
String imagePath = "D:/" + path + imageName;
String savePath = saveUrl + imagePath;
File directory = new File(imageDir);
if (!directory.exists()) {
directory.mkdirs();
}
BufferedImage image = reader.renderImage(i, 1.5f);
//生成图片,保存位置
File imageFile = new File(savePath);
FileOutputStream out = new FileOutputStream(imageFile);
//使用png的清晰度
ImageIO.write(image, "png", out);
//将图片路径追加到网页文件里-此处在服务器上应使用url地址
String url = "D:/"+ imagePath;
buffer.append("<img src=\"" + url + "\"/>\r\n");
image = null;
out.flush();
out.close();
}
return buffer;
}
上述内容只是提供一个简单的实现思路和代码demo,具体使用时还需要根据实际情况具体分析,而且pdf转换成图片之后的效果也不是很好,不建议使用,还是建议前端使用pdf插件实现预览,效果更好,毕竟是一个使用很广泛的插件.