PDFBox 3.0.1无PDDocument.load(url)方法,如何从URL加载PDF?
PDFBox 3.0.1 从URL加载PDF的正确实现方案
你的代码核心问题是直接将InputStream强转为RandomAccessRead——InputStream并未实现该接口,类型转换必然失败,导致PDF加载出错。以下是两种可行的替代方案:
方案一:内存缓存加载(适合小文件)
使用RandomAccessBuffer将URL输入流缓存到内存中,它实现了RandomAccessRead接口,能直接被Loader.loadPDF接收:
public void loadPDF(String url, String name) throws IOException { PDDocument document = null; URL pdfUrl = new URL(url); try (InputStream inputStream = pdfUrl.openStream(); RandomAccessRead randomAccessRead = new RandomAccessBuffer(inputStream)) { document = Loader.loadPDF(randomAccessRead); // 在此处添加对document的业务操作 } catch (IOException e) { Assert.fail("加载PDF失败,请检查URL:" + e.getMessage()); } finally { if (document != null) { document.close(); } } }
方案二:临时文件缓存加载(适合大文件)
如果PDF文件较大,内存缓存可能导致溢出,建议先将文件下载到临时文件,再从文件加载:
public void loadPDF(String url, String name) throws IOException { PDDocument document = null; URL pdfUrl = new URL(url); // 创建自动清理的临时文件 File tempFile = File.createTempFile("temp_pdf_", ".pdf"); tempFile.deleteOnExit(); try (InputStream inputStream = pdfUrl.openStream(); FileOutputStream outputStream = new FileOutputStream(tempFile)) { // 将URL内容写入临时文件 byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = inputStream.read(buffer)) != -1) { outputStream.write(buffer, 0, bytesRead); } // 从临时文件加载PDF document = Loader.loadPDF(tempFile); // 在此处添加对document的业务操作 } catch (IOException e) { Assert.fail("加载PDF失败,请检查URL:" + e.getMessage()); } finally { if (document != null) { document.close(); } // 手动删除临时文件,确保资源清理 tempFile.delete(); } }
额外优化建议
- 添加网络超时设置,避免请求长时间阻塞:
URLConnection urlConnection = pdfUrl.openConnection(); urlConnection.setConnectTimeout(5000); // 连接超时5秒 urlConnection.setReadTimeout(10000); // 读取超时10秒 InputStream inputStream = urlConnection.getInputStream();
- 确保依赖正确(Maven示例):
<dependency> <groupId>org.apache.pdfbox</groupId> <artifactId>pdfbox</artifactId> <version>3.0.1</version> </dependency>
内容的提问来源于stack exchange,提问作者Ayush Garg
相关产品推荐
相关产品推荐

