出于某些需求需要將一張簡單的圖片轉(zhuǎn)換為PDF的文件格式,因此自己動手寫了一個圖片轉(zhuǎn)換PDF的系統(tǒng),現(xiàn)在將該系統(tǒng)分享在這里,供大家參考。
(學習視頻推薦:java課程)
具體代碼:
引入依賴:
<!--該項目以SpringBoot為基礎搭建--> <parent> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-parent</artifactId> <version>2.0.4.RELEASE</version> <relativePath/> </parent> <dependencies> <!--SpringMVC的依賴,方便我們可以獲取前端傳遞過來的文件信息--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <!--ITextPdf,操作PDF文件的工具類--> <dependency> <groupId>com.itextpdf</groupId> <artifactId>itextpdf</artifactId> <version>5.4.2</version> </dependency> </dependencies>
前端頁面:
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>圖片轉(zhuǎn)換Pdf</title> <style> .submitButton { margin-top: 20px; margin-left: 150px; background-color: #e37e10; border-radius: 10px; border: 1px solid #ff8300; } </style> </head> <body> <div style="text-align: center"> <h1>圖片轉(zhuǎn)換pdf工具</h1> <form action="/pdf/image/to" enctype="multipart/form-data" method="post" onsubmit="return allowFileType()"> <input type="file" id="file" name="file" placeholder="請選擇圖片" onchange="allowFileType()" style="border: 1px solid black;"><br> <input type="submit" value="一鍵轉(zhuǎn)換pdf文件"> </form> </div> </body> <script> function allowFileType() { let file = document.getElementById("file").files[0]; let fileName = file.name; console.log(fileName) let fileSize = file.size; console.log(fileSize) let suffix = fileName.substring(fileName.lastIndexOf("."),fileName.length); if('.jpg' != suffix && '.png' != suffix) { alert("目前只允許傳入.jpg或者.png格式的圖片!"); return false; } if(fileSize > 2*1024*1024) { alert("上傳圖片不允許超過2MB!"); return false; } return true; } </script> </html>
(推薦教程:java入門教程)
控制層接口
package com.hrp.controller; import com.hrp.util.PdfUtils; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; /** * @description: 用于處理Pdf相關的請求 */ @Controller @RequestMapping("pdf") public class PdfController { @PostMapping("image/to") public void imageToPdf(@RequestParam("file") MultipartFile file,HttpServletResponse response) throws Exception{ PdfUtils.imageToPdf(file,response); } }
PDF工具類
package com.hrp.util; import com.itextpdf.text.Document; import com.itextpdf.text.DocumentException; import com.itextpdf.text.Image; import com.itextpdf.text.PageSize; import com.itextpdf.text.pdf.PdfWriter; import org.springframework.stereotype.Component; import org.springframework.web.multipart.MultipartFile; import javax.servlet.http.HttpServletResponse; import java.io.*; import java.net.URLEncoder; /** * @description: pdf相關的工具類 */ @Component public class PdfUtils { /** * 圖片轉(zhuǎn)換PDF的公共接口 * * @param file SpringMVC獲取的圖片文件 * @param response HttpServletResponse * @throws IOException IO異常 * @throws DocumentException PDF文檔異常 */ public static void imageToPdf(MultipartFile file, HttpServletResponse response) throws IOException, DocumentException { File pdfFile = generatePdfFile(file); downloadPdfFile(pdfFile, response); } /** * 將圖片轉(zhuǎn)換為PDF文件 * * @param file SpringMVC獲取的圖片文件 * @return PDF文件 * @throws IOException IO異常 * @throws DocumentException PDF文檔異常 */ private static File generatePdfFile(MultipartFile file) throws IOException, DocumentException { String fileName = file.getOriginalFilename(); String pdfFileName = fileName.substring(0, fileName.lastIndexOf(".")) + ".pdf"; Document doc = new Document(PageSize.A4, 20, 20, 20, 20); PdfWriter.getInstance(doc, new FileOutputStream(pdfFileName)); doc.open(); doc.newPage(); Image image = Image.getInstance(file.getBytes()); float height = image.getHeight(); float width = image.getWidth(); int percent = getPercent(height, width); image.setAlignment(Image.MIDDLE); image.scalePercent(percent); doc.add(image); doc.close(); File pdfFile = new File(pdfFileName); return pdfFile; } /** * * 用于下載PDF文件 * * @param pdfFile PDF文件 * @param response HttpServletResponse * @throws IOException IO異常 */ private static void downloadPdfFile(File pdfFile, HttpServletResponse response) throws IOException { FileInputStream fis = new FileInputStream(pdfFile); byte[] bytes = new byte[fis.available()]; fis.read(bytes); fis.close(); response.reset(); response.setHeader("Content-Type", "application/pdf"); response.setHeader("Content-Disposition", "attachment; filename=" + URLEncoder.encode(pdfFile.getName(), "UTF-8")); OutputStream out = response.getOutputStream(); out.write(bytes); out.flush(); out.close(); } /** * 等比壓縮,獲取壓縮百分比 * * @param height 圖片的高度 * @param weight 圖片的寬度 * @return 壓縮百分比 */ private static int getPercent(float height, float weight) { float percent = 0.0F; if (height > weight) { percent = PageSize.A4.getHeight() / height * 100; } else { percent = PageSize.A4.getWidth() / weight * 100; } return Math.round(percent); } }
實現(xiàn)效果:
網(wǎng)站題目:利用java實現(xiàn)一個圖片轉(zhuǎn)PDF文件工具
文章位置:http://sd-ha.com/article28/cjchjp.html
成都網(wǎng)站建設公司_創(chuàng)新互聯(lián),為您提供外貿(mào)網(wǎng)站建設、標簽優(yōu)化、搜索引擎優(yōu)化、響應式網(wǎng)站、手機網(wǎng)站建設、定制網(wǎng)站
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)