package com.dpkj.modules.print.utils; import com.dpkj.common.exception.RRException; import lombok.extern.slf4j.Slf4j; import java.io.FileOutputStream; import java.io.InputStream; import java.net.HttpURLConnection; import java.net.URL; @Slf4j public class PDFUtils { private static final String defaultPath = "D:/images"; public enum AddressType { HTTP, LOCAL, OTHER, UNKNOWN } /** * 校验地址类型 * @param address 地址 */ public static AddressType checkAddressType(String address) { if (address == null || address.isEmpty()) { return AddressType.UNKNOWN; } // 检查是否为 HTTP 或 HTTPS 地址 if (address.startsWith("http://") || address.startsWith("https://")) { return AddressType.HTTP; } // 简单判断是否为本地地址 // 本地地址可能以文件协议 file:// 开头,或者是一个相对路径或绝对路径 if (address.startsWith("file://") || (address.contains(":") && address.contains("\\")) || (address.startsWith("/"))) { return AddressType.LOCAL; } return AddressType.OTHER; } public static String downloadPdf(String pdfUrl) { String savePath = defaultPath + "/genera_image_" + System.currentTimeMillis() + ".pdf"; try { // 创建 URL 对象 URL url = new URL(pdfUrl); // 打开 HTTP 连接 HttpURLConnection connection = (HttpURLConnection) url.openConnection(); // 设置请求方法为 GET connection.setRequestMethod("GET"); // 获取响应码 int responseCode = connection.getResponseCode(); if (responseCode == HttpURLConnection.HTTP_OK) { // 获取输入流 try (InputStream inputStream = connection.getInputStream(); // 创建文件输出流 FileOutputStream outputStream = new FileOutputStream(savePath)) { byte[] buffer = new byte[4096]; int bytesRead; // 循环读取数据并写入文件 while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } log.info("PDF 文件下载成功,保存路径: " + savePath); } } else { log.error("下载失败,响应码: " + responseCode); } // 断开连接 connection.disconnect(); }catch (Exception e) { throw new RRException("PDF文件下载失败"); } return savePath; } }