首先需要導入相關依賴,由于具體依賴本人也不是記得很清楚了,所以簡短的說一下。
-
iText:PDF 操作庫,用于創建和操作 PDF 文件。可通過 Maven 或 Gradle 引入 iText 依賴。
-
MultipartFile:Spring 框架中處理文件上傳的類。通常用于接收前端上傳的文件數據。
-
HttpServletRequest:Java Servlet API 中的類,用于獲取 HTTP 請求的相關信息,如請求方式、參數等。
-
BufferedImage:Java 中用于表示圖像的類,通常與 ImageIO 結合使用來讀取圖片文件。
-
ByteArrayOutputStream:Java 中的字節數組輸出流,用于將數據寫入到字節數組中。
-
Document和PdfWriter:iText 庫中的類,分別用于創建 PDF 文檔和寫入 PDF 文件。
-
Image:iText 庫中的類,用于處理圖像,并將圖像添加到 PDF 文檔中。
-
Rectangle:iText 庫中的類,用于表示 PDF 頁面的大小。
<!--ITextPdf,操作PDF文件的工具類--><dependency><groupId>com.itextpdf</groupId><artifactId>itextpdf</artifactId><version>5.4.2</version></dependency><dependency><groupId>com.documents4j</groupId><artifactId>documents4j-local</artifactId><version>1.0.3</version></dependency><dependency><groupId>com.documents4j</groupId><artifactId>documents4j-transformer-msoffice-word</artifactId><version>1.0.3</version></dependency>
以上提供一些依賴,是需要用到的,然后在application.yml中添加以下配置:
web:upload-path: E:/PictureTool/resources:static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,file:${web.upload-path}
- 配置
web.upload-path
為與項目代碼分離的靜態資源路徑,即:文件上傳保存根路徑 - 配置
spring.resources.static-locations
,除了帶上Spring Boot默認的靜態資源路徑之外,加上file:${web.upload-path}指向外部的文件資源上傳路徑。該路徑下的靜態資源可以直接對外提供HTTP訪問服務。
然后就需要寫具體的實現邏輯了:
public R imgToPdf(MultipartFile file, HttpServletRequest request) {// 獲取文件在服務器上的存儲路徑String imagePath = getFilePath(file);// 獲取文件名,去掉文件擴展名String filename = file.getOriginalFilename().substring(0, file.getOriginalFilename().lastIndexOf("."));// 將文件名賦值給成員變量FileNameFileName = filename;try {// 使用ImageIO讀取文件內容,轉換為BufferedImage對象BufferedImage img = ImageIO.read(new File(imagePath));// 創建一個ByteArrayOutputStream對象,用于存儲轉換后的PDF文件ByteArrayOutputStream baos = new ByteArrayOutputStream();// 創建一個Document對象,用于存儲PDF文檔Document doc = new Document();// 創建一個PdfWriter對象,用于將BufferedImage對象轉換為PDF文件PdfWriter.getInstance(doc, new FileOutputStream(uploadPath + filename + ".pdf"));// 存儲PDF文件的路徑FilePath = uploadPath + filename + ".pdf";System.out.println(uploadPath + filename + ".pdf");// 打開文檔doc.open();// 將BufferedImage對象添加到PDF文檔中Image image = Image.getInstance(imagePath);// 設置文檔的頁面大小為BufferedImage的大小doc.setPageSize(new Rectangle(img.getWidth(), img.getHeight()));// 將BufferedImage對象添加到PDF文檔的第一個頁面doc.add(image);// 關閉文檔doc.close();// 調用addUserOperation方法,記錄用戶操作boolean re = addUserOperation(file, "pdf", 1, request);System.out.println("轉換成功,re為" + re);// 獲取PDF文件的下載鏈接String downloadLink = request.getScheme() + "://" + request.getServerName() + ":" +request.getServerPort() + request.getContextPath() + "/pictureTool/" + filename + ".pdf";// 返回PDF文件的下載鏈接return R.Success("圖片轉pdf轉換成功", downloadLink);} catch (Exception e) {// 如果轉換失敗,記錄用戶操作e.printStackTrace();boolean re = addUserOperation(file, "pdf", 0, request);System.out.println("轉換失敗,re為" + re);// 返回錯誤信息return R.Failed(500, "圖片轉換失敗");}}
以上代碼接受一個文件,然后進行轉換為pdf并保存在本地指定的文件夾中,接下來使用輸出流的方式進行文件下載。
public R downloadFile(HttpServletRequest request, HttpServletResponse response)throws IOException {// 獲取文件路徑和文件名String filePath = FilePath;String fileName = FileName;// 設置響應頭,指定下載文件的名稱response.setHeader("Content-Disposition","attachment; filename=" + java.net.URLEncoder.encode(fileName, "UTF-8"));try {// 打開文件File file = new File(filePath);FileInputStream fileInputStream = new FileInputStream(file);// 讀取文件內容到字節數組byte[] fileByte = new byte[(int) file.length()];ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();byte[] bytes = new byte[1024];int len;while ((len = fileInputStream.read(bytes, 0, bytes.length)) != -1) {byteArrayOutputStream.write(bytes, 0, len);}byteArrayOutputStream.close();fileByte = byteArrayOutputStream.toByteArray();// 將文件內容寫入響應對象OutputStream outputStream = response.getOutputStream();outputStream.write(fileByte);outputStream.flush();outputStream.close();// 返回成功信息return R.Success("文件下載成功");} catch (Exception e) {// 如果下載失敗,返回失敗信息e.printStackTrace();return R.Failed("文件下載失敗");}}
其中R是我自定義的一個響應類,改成你自己的就可以了~
最后,記得放行你存放文件的盤符: