java pdf输出图片_Java PDF转换成图片并输出给前台展示

本文介绍如何使用Java将PDF转换为PNG图片,并将图片转换为Base64编码,以便通过Ajax在前端展示。主要涉及Apache PDFBox库和Hutool工具包的使用。
摘要由CSDN通过智能技术生成

首先需要导入所需工具类

org.apache.pdfbox

fontbox

2.0.1

org.apache.pdfbox

pdfbox

2.0.1

cn.hutool

hutool-all

4.1.19

1、PDF转图片的方法    for那里看看是几张图片。 几页。根据页数进行转

/***

* PDF文件转PNG图片,全部页数

*

* @param PdfFilePath pdf完整路径

* @param dpi dpi越大转换后越清晰,相对转换速度越慢

* @return

*/

public static String pdf2Image(String PdfFilePath, String dstImgFolder, int dpi) {

File file = new File(PdfFilePath);

PDDocument pdDocument;

try {

String imgPDFPath = file.getParent();

int dot = file.getName().lastIndexOf('.');

String imagePDFName = file.getName().substring(0, dot); // 获取图片文件名

String imgFolderPath = dstImgFolder;

pdDocument = PDDocument.load(file);

PDFRenderer renderer = new PDFRenderer(pdDocument);

/* dpi越大转换后越清晰,相对转换速度越慢 */

StringBuffer imgFilePath = null;

for (int i = 1; i < 2; i++) {

String imgFilePathPrefix = imgFolderPath + File.separator + imagePDFName;

imgFilePath = new StringBuffer();

imgFilePath.append(imgFilePathPrefix);

imgFilePath.append(".png");

File dstFile = new File(imgFilePath.toString());

BufferedImage image = renderer.renderImageWithDPI(i, dpi);

ImageIO.write(image, "png", dstFile);

}

System.out.println("PDF文档转PNG图片成功!");

return imgFilePath.toString();

} catch (IOException e) {

e.printStackTrace();

return null;

}

}

2、调用这个方法  生成BASE64数据

String s = wpath + BRCA + "-" + CTNND1_15951 + "-KMplot.pdf";

//转换返回图片地址

String s1 = pdf2Image(s, wpath, 300);

File file = new File(s1);

//把图片转换为BASE64数据

FileInputStream inputFile = new FileInputStream(file);

byte[] buffer = new byte[(int) file.length()];

inputFile.read(buffer);

inputFile.close();

String ss = new BASE64Encoder().encode(buffer);

3、使用ajax的方式将图片数据取回。直接设置如IMG标签中

img就是取回的数据

完整的ajax代码

var index = layer.load();

$.ajax({

type:"post",

dataType:"json",

contentType:'application/json;charset=UTF-8',

url:"getTnImg",

data:JSON.stringify(data),

success:function(resp){

layer.close(index);

var img = resp.img;

var html = '';

layer.open({

type: 1,

skin: 'layui-layer-rim', //加上边框

area: ['50%', '90%'], //宽高

content: html

});

},

error:function(XMLHttpRequest,textStatus,errorThrown) {

console.log(XMLHttpRequest.status);

console.log(XMLHttpRequest.statusText);

}

});

来源:https://www.cnblogs.com/jxldjsn/p/10951854.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值