日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問(wèn) 生活随笔!

生活随笔

當(dāng)前位置: 首頁(yè) > 编程资源 > 编程问答 >内容正文

编程问答

微信小程序实现PDF转图片(java spring实现)

發(fā)布時(shí)間:2023/12/29 编程问答 30 豆豆
生活随笔 收集整理的這篇文章主要介紹了 微信小程序实现PDF转图片(java spring实现) 小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.

微信小程序?qū)崿F(xiàn)PDF轉(zhuǎn)圖片前后端(兩種方式)

  • 1、前端傳PDF的url地址至后端
    • 1.1前端
    • 1.2后端
  • 2、前端傳PDF文件至后端
    • 2.1前端
    • 2.2后端

1、前端傳PDF的url地址至后端

1.1前端

轉(zhuǎn)換的圖片頁(yè)面 示例。

<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,//轉(zhuǎn)換完的圖片地址imagePath:''}},onLoad(options) {//監(jiān)聽(tīng)頁(yè)面?zhèn)髦? 通過(guò)uni.$emit("contractInfo",val);傳過(guò)來(lái)uni.$once("contractInfo",res =>{this.contract = res;console.log("res",res);this.pdfToImage();});},methods:{pdfToImage(){let that = this;//responseType的類型必須為arraybufferglobal.$http.request({url:'admin/pdfToImg/fileToImgFromUrl',method:'post',responseType: 'arraybuffer',data: { 'url':that.contract.contractPath,'urlName':that.contract.contractNumber}}).then(res=>{//將文件轉(zhuǎn)化為二進(jìn)制數(shù)據(jù)var base64 = wx.arrayBufferToBase64(res.data);console.log("圖片",base64);//圖片為本地地址that.imagePath = 'data:image/png;base64,' + base64console.log("圖片",that.imagePath);that.flag = true;}).catch(err=>{console.log(err)});},}}</script> <style lang="scss">#pdfImage{width: 100%;} </style>

1.2后端

control層。

/** * 從網(wǎng)頁(yè)下載pdf,轉(zhuǎn)換為圖片,返回前端* @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();//設(shè)置超時(shí)間為3秒conn.setConnectTimeout(5*1000);//防止屏蔽程序抓取而返回403錯(cuò)誤conn.setRequestProperty("User-Agent", "Mozilla/4.0 (compatible; MSIE 5.0; Windows NT; DigExt)");//得到輸入流InputStream inputStream = conn.getInputStream();//獲取自己數(shù)組,調(diào)用方法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);}}}//刪除臨時(shí)文件方法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);} }/** * 從輸入流中獲取字節(jié)數(shù)組* @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(); }/*** 刪除本地臨時(shí)文件* @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 轉(zhuǎn) 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();} }

引用出處

鏈接:
springMVC將PDF轉(zhuǎn)換成圖片
MultipartFile轉(zhuǎn)File

總結(jié)

以上是生活随笔為你收集整理的微信小程序实现PDF转图片(java spring实现)的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。

如果覺(jué)得生活随笔網(wǎng)站內(nèi)容還不錯(cuò),歡迎將生活随笔推薦給好友。