PDF document readers never close their PDDocument and are not Closeable
Bug description
PagePdfDocumentReader and ParagraphPdfDocumentReader parse a PDDocument in their
constructor and hold it in a protected final PDDocument document field. Nothing ever calls
document.close(), and neither reader implements Closeable, so a caller has no way to close it
either. Every reader instance keeps a fully parsed PDF, and the PDFBox resources behind it, alive
for as long as the reader is reachable.
PDDocument.close() is not a formality in PDFBox 3. It releases, in order:
signingSupport- the
COSDocument, which in turn closes everyCOSStreamin the object pool and the stream cache pdfSource, theRandomAccessReadholding the document bytes- everything in
fontsToClose—TrueTypeFontinstances registered while text is extracted, which can wrap open handles to embedded or system font files
PagePdfDocumentReader.get() runs PDFLayoutTextStripperByArea over every page, so the font path
is exercised on the normal read, not just on unusual documents.
Environment
Spring AI 2.0.2-SNAPSHOT (main), PDFBox 3.0.7, Java 17.
Steps to reproduce
The documented ETL usage is a loop over a directory:
for (Resource pdf : pdfs) {
var documents = new PagePdfDocumentReader(pdf, config).get();
vectorStore.add(textSplitter.apply(documents));
}Each iteration constructs a reader whose PDDocument is never closed. Nothing in the public API
lets the caller fix this — the field is protected, and the class exposes no close().
Expected behavior
A caller should be able to release the parsed document deterministically, and the readers should not depend on garbage collection to do it.
Notes / possible directions
I do not want to guess at the API here, so raising it rather than sending a PR blind. The options I can see:
implements Closeableon both readers, delegating todocument.close(). Adding an interface is source- and binary-compatible, and callers opt in with try-with-resources. Existing callers keep leaking, though, because they will not know to close.- Close the
PDDocumentat the end ofget(). Every documented usage treatsget()as terminal, and this fixes existing callers with no code change on their side — but it silently makes the readers single-use, so a secondget()would need to fail with a clear message rather than misbehave. - Both:
Closeablefor explicit lifecycle management, plus release inget()for the common path.
TikaDocumentReader does not have this problem — it reads inside try-with-resources and keeps no
document object — so the two PDF readers are the odd ones out among the readers in the tree.
Happy to open a PR for whichever direction you prefer.
Related: the stream-level half of this (the InputStream handed to RandomAccessReadBuffer was
also never closed) is fixed separately in the PDF reader stream-leak PR; this issue is about the
PDDocument itself, which that PR deliberately leaves alone.
Source: spring-projects/spring-ai