微信小程序实现PDF转图片前后端(两种方式)
1、前端传PDF的url地址至后端
1.1前端
转换的图片页面 示例
。
<template>
<view class="detail-desc">
<view v-if='flag'>
<image id="pdfImage" :src="imagePath" mode="widthFix"></image>
<button style="border-radius:160rpx;margin-bottom: 40upx;width: 70%;margin-top: 20upx;" type="warn"
@click="agree">确定</button>
</view>
</view>
</template>
<script>
export default{
data(){
return{
//PDF信息
contract:{},
flag:false,
//转换完的图片地址
imagePath:''
}
},
onLoad(options) {
//监听页面传值 通过uni.$emit("contractInfo",val);传过来
uni.$once("contractInfo",res =>{
this.contract = res;
console.log("res",res);
this.pdfToImage();
});
},
methods:{
pdfToImage(){
let that = this;
//responseType的类型必须为arraybuffer
global.$http.request({
url:'admin/pdfToImg/fileToImgFromUrl',
method:'post',
responseType: 'arraybuffer',
data: {
'url':that.contract.contractPath,
'urlName':that.contract.contractNumber
}
}).then(
res=>{
//将文件转化为二进制数据
var base64 = wx.arrayBufferToBase64(res.data);
console.log("图片",base64);
//图片为本地地址
that.imagePath = 'data:image/png;base64,' + base64
console.log("图片",that.imagePath);
that.flag = true;
}
).catch(err=>{
console.log(err)
});
},
}
}
</script>
<style lang="scss">
#pdfImage{
width: 100%;
}
</style>
1.2后端
control层
。
/**
* 从网页下载pdf,转换为图片,返回前端
* @param urlStr
* @param urlName
* @return
* @throws Exception
*/
@RequestMapping(value = "/fileToImgFromUrl")
public ResponseEntity<byte[]> fileToImgFromUrl(
@RequestParam("url") String urlStr,
@RequestParam("urlName") String urlName
) throws Exception {
List<BufferedImage> images = new ArrayList<>();
//PDF的url地址
URL url = new URL(urlStr);
HttpURLConnection conn = (HttpURLConnection)url.openConnection();
//设置超时间为3秒
conn.setConnectTimeout(5*1000);
//防止屏蔽程序抓取而返回403错误
conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");
//得到输入流
InputStream inputStream = conn.getInputStream();
//获取自己数组,调用方法
byte[] getData = readInputStream(inputStream);
//文件名称
File file = new File(urlName);
FileOutputStream fos = new FileOutputStream(file);
fos.write(getData);
if(fos!=null){
fos.close();
}
if(inputStream!=null){
inputStream.close();
}
System.out.println("info:"+url+" download success");
try (PDDocument pdDocument = PDDocument.load(file)) {
PDFRenderer pdfRenderer = new PDFRenderer(pdDocument);
for (int i = 0; i < pdDocument.getNumberOfPages(); i++) {
BufferedImage image = pdfRenderer.renderImageWithDPI(i, 192f);
if (image != null) {
images.add(image);
}
}
}
//删除临时文件方法
delteTempFile(file);
// 拼接图片
int width = 0, height = 0;
for (BufferedImage image : images) {
width = image.getWidth() > width ? image.getWidth() : width;
height += image.getHeight();
}
BufferedImage pdfImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = pdfImage.createGraphics();
height = 0;
for (BufferedImage image : images) {
g2d.drawImage(image, (width - image.getWidth()) / 2, height, image.getWidth(), image.getHeight(), null);
height += image.getHeight();
}
g2d.dispose();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
ImageIO.write(pdfImage, "jpg", os);
return new ResponseEntity<>(os.toByteArray(), headers, HttpStatus.OK);
}
}
/**
* 从输入流中获取字节数组
* @param inputStream
* @return
* @throws IOException
*/
public static byte[] readInputStream(InputStream inputStream) throws IOException {
byte[] buffer = new byte[1024];
int len = 0;
ByteArrayOutputStream bos = new ByteArrayOutputStream();
while((len = inputStream.read(buffer)) != -1) {
bos.write(buffer, 0, len);
}
bos.close();
return bos.toByteArray();
}
/**
* 删除本地临时文件
* @param file
*/
public static void delteTempFile(File file) {
if (file != null) {
File del = new File(file.toURI());
del.delete();
}
}
2、前端传PDF文件至后端
2.1前端
wx.uploadFile({
url: 'http://localhost:9092/admin/pdfToImg/fileToImg',
filePath: filePath,
name: 'file',
header:{
responseType: 'arraybuffer'
},
success (res){
let url = "data:image/png;base64," + wx.arrayBufferToBase64(res.data);
}
})
2.2后端
/**
* 前端上传pdf至后端
* @param file
* @return
* @throws Exception
*/
@RequestMapping(value = "/fileToImg")
public ResponseEntity<byte[]> fileToImg(
MultipartFile file
) throws Exception {
List<BufferedImage> images = new ArrayList<>();
if (file == null) {
return new ResponseEntity<>(HttpStatus.NOT_FOUND);
}
File pdfFile = multipartFileToFile(file);
try (PDDocument pdDocument = PDDocument.load(pdfFile)) {
PDFRenderer pdfRenderer = new PDFRenderer(pdDocument);
for (int i = 0; i < pdDocument.getNumberOfPages(); i++) {
BufferedImage image = pdfRenderer.renderImageWithDPI(i, 192f);
if (image != null) {
images.add(image);
}
}
}
delteTempFile(pdfFile);
// 拼接图片
int width = 0, height = 0;
for (BufferedImage image : images) {
width = image.getWidth() > width ? image.getWidth() : width;
height += image.getHeight();
}
BufferedImage pdfImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2d = pdfImage.createGraphics();
height = 0;
for (BufferedImage image : images) {
g2d.drawImage(image, (width - image.getWidth()) / 2, height, image.getWidth(), image.getHeight(), null);
height += image.getHeight();
}
g2d.dispose();
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.IMAGE_JPEG);
try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
ImageIO.write(pdfImage, "jpg", os);
return new ResponseEntity<>(os.toByteArray(), headers, HttpStatus.OK);
}
}
/**
* MultipartFile 转 File
*
* @param file
* @throws Exception
*/
public static File multipartFileToFile(MultipartFile file) throws Exception {
File toFile = null;
if (file.equals("") || file.getSize() <= 0) {
file = null;
} else {
InputStream ins = null;
ins = file.getInputStream();
toFile = new File(file.getOriginalFilename());
inputStreamToFile(ins, toFile);
ins.close();
}
return toFile;
}
//获取流文件
private static void inputStreamToFile(InputStream ins, File file) {
try {
OutputStream os = new FileOutputStream(file);
int bytesRead = 0;
byte[] buffer = new byte[8192];
while ((bytesRead = ins.read(buffer, 0, 8192)) != -1) {
os.write(buffer, 0, bytesRead);
}
os.close();
ins.close();
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取流文件
* @param ins
* @param file
*/
public static void delteTempFile(File file) {
if (file != null) {
File del = new File(file.toURI());
del.delete();
}
}
引用出处