spring-ai icon indicating copy to clipboard operation
spring-ai copied to clipboard

Support specific page ranges in `PagePdfDocumentReader`

Open WangJincheng4869 opened this issue 5 months ago • 4 comments

Expected Behavior It would be highly beneficial if PagePdfDocumentReader supported extracting text from specific page ranges rather than processing the entire PDF document. This feature would allow users to easily define which pages to parse, effectively skipping useless pages such as covers, tables of contents, copyright pages, blank pages, and appendices.

Ideally, this could be configured via PdfDocumentReaderConfig. The page range data type could be an array of integer pairs (e.g., int[][] like {{3, 50}, {55, 100}}) or a string expression.

Code Example:

PdfDocumentReaderConfig config = PdfDocumentReaderConfig.builder()
    // Only process pages 3-50 and 55-100, skipping the cover, TOC, and blank pages
    .withPageRanges(new int[][]{{3, 50}, {55, 100}}) 
    .withPagesPerDocument(1)
    .build();

PagePdfDocumentReader reader = new PagePdfDocumentReader(new FileSystemResource("document.pdf"), config);
List<Document> documents = reader.get(); 

Current Behavior Currently, PagePdfDocumentReader iterates through the entire PDPageTree from the first page to the last page. The PdfDocumentReaderConfig only provides pagesPerDocument to group parsed pages, but there is no way to skip or filter out unwanted pages during the parsing phase.

Furthermore, attempting to extend PagePdfDocumentReader to implement this feature manually is difficult because critical internal methods like handleSinglePage and the config field are marked as private, forcing developers to copy-paste and rewrite the core extraction logic.

Context

  • Why do you need this feature? In enterprise RAG (Retrieval-Augmented Generation) pipelines, PDFs often contain irrelevant information such as covers, tables of contents, prefaces, blank pages, or appendices. Parsing these pages introduces significant noise into the vector database, degrades retrieval accuracy, and wastes Embedding API costs and LLM context windows. We need a native way to define page ranges to exclude these sections and improve data quality.
  • Alternatives considered: I considered subclassing PagePdfDocumentReader and overriding the get() method. However, due to the private access modifiers on handleSinglePage and config, the subclass ends up duplicating a lot of boilerplate code, which is not maintainable.
  • Workarounds: The only current workaround is to use external tools (like qpdf or pdftk) to physically split the PDF or remove specific pages before feeding them to Spring AI, which adds unnecessary I/O overhead and complexity to the ETL pipeline.

Expected Behavior (期望行为) 如果 PagePdfDocumentReader 能够支持仅提取特定页码范围的文本,而不是强制解析整个 PDF 文档,那将非常实用。此功能将允许用户自定义需要解析的页面,从而轻松跳过无用的页面,如封面、目录、版权页、空白页和附录。

理想情况下,这可以通过 PdfDocumentReaderConfig 进行配置。页码范围的数据类型可以是整数对数组(例如 int[][],如 {{3, 50}, {55, 100}})或字符串表达式。

代码示例:

PdfDocumentReaderConfig config = PdfDocumentReaderConfig.builder()
    // 仅处理 3-50 页和 55-100 页,跳过封面、目录和空白页
    .withPageRanges(new int[][]{{3, 50}, {55, 100}}) 
    .withPagesPerDocument(1)
    .build();

PagePdfDocumentReader reader = new PagePdfDocumentReader(new FileSystemResource("document.pdf"), config);
List<Document> documents = reader.get(); 

Current Behavior (当前行为) 目前,PagePdfDocumentReader 会遍历整个 PDPageTree,从第一页一直处理到最后一页。PdfDocumentReaderConfig 仅提供了 pagesPerDocument 用于将解析后的页面分组,但无法在解析阶段跳过或过滤掉不需要的页面。

此外,尝试通过继承 PagePdfDocumentReader 来手动实现此功能非常困难,因为关键的内部方法(如 handleSinglePage)和 config 属性都被标记为 private,这迫使开发者必须复制并重写核心的文本提取逻辑。

Context (背景/上下文)

  • 为什么需要这个功能? 在企业级 RAG(检索增强生成)数据管道中,PDF 文件通常包含大量无关信息,如封面、目录、前言、空白页或附录。解析这些页面会给向量数据库引入严重的噪音,降低检索准确率,并白白浪费 Embedding API 的成本和 LLM 的上下文窗口。我们需要一种原生的方式来定义页码范围,以剔除这些无关部分,从而提升数据质量。
  • 考虑过的替代方案: 我曾考虑继承 PagePdfDocumentReader 并重写 get() 方法。但是,由于 handleSinglePage 和 config 的 private 访问修饰符,子类最终会重复大量样板代码,非常不利于维护。
  • 目前的变通方法(Workarounds): 目前唯一的变通方法是在将 PDF 喂给 Spring AI 之前,使用外部工具(如 qpdf 或 pdftk)物理切割 PDF 或删除特定页面。这给 ETL 管道增加了不必要的 I/O 开销和复杂性。

WangJincheng4869 avatar Jun 09 '26 10:06 WangJincheng4869

To “define page ranges to skip covers, tables of contents, prefaces, blank pages, or appendices, thereby reducing RAG noise and embedding cost” is not without value. Page-range filtering can exist as a manual override or a low-cost coarse filtering mechanism.

However, it is not suitable as the core solution for enterprise-grade RAG data cleaning. The physical page index of a PDF, the printed page numbers in the document, and the actual semantic structure of the pages do not have a stable one-to-one mapping. Some documents use i, ii, iii for front matter, some start page 1 only at the main body, and while some appendices are noise, others may contain field definitions, metric rules, formulas, or parameter tables. Skipping pages purely by page number can easily remove valuable information.

More importantly, if the system can already determine that a page is a cover, table of contents, blank page, or irrelevant appendix, then it has already performed some form of content parsing or page classification. If the content has not yet been parsed, it is hard to reliably decide whether a page should be skipped based on page numbers alone. This is essentially a chicken-and-egg problem.

Therefore, a more reasonable design is to treat page-range filtering as an optional manual rule, while introducing page classification based on content, layout, and document structure. For example, the pipeline can identify structural labels such as cover, table of contents, blank page, body, appendix, references, tables, and figures, and then use policy rules to decide which pages should be embedded, which should only be kept as metadata, which should be excluded, and which should be preserved as document navigation information.

In short, PDF page-range filtering is a useful fallback capability, but it is not a stable data-quality solution. To truly reduce noise in enterprise RAG pipelines, we should rely on content-level page classification and structured extraction, rather than using “page number” as a proxy for “page meaning.”


“通过定义页码范围来跳过封面、目录、前言、空白页、附录,从而减少 RAG 噪声和 Embedding 成本”这个需求并不是完全没有价值。页码范围过滤可以作为一种人工 override 或低成本粗过滤能力存在。但它不适合作为企业级 RAG 数据清洗的核心方案。因为 PDF 的物理页码、文档中印刷出来的页码,以及页面的真实语义结构,并不存在稳定的一一对应关系。有的文档前几页是 i、ii、iii,有的正文才从 1 开始,有的附录是噪声,但有的附录恰恰包含字段说明、指标口径、公式或参数表,直接按页码跳过很容易遗漏有效信息。

更关键的是,如果系统已经能判断某一页是封面、目录、空白页或无关附录,那它其实已经做了某种内容解析或页面分类;而如果还没有解析内容,就很难仅凭页码稳定判断是否应该跳过。这本身就是一个“先有鸡还是先有蛋”的问题。

所以,更合理的设计是把页码范围过滤作为可选的人工规则,同时引入基于内容、版式和文档结构的页面分类能力,例如识别 cover、TOC、blank page、body、appendix、references、tables、figures 等结构标签,再由策略决定哪些页面入库、哪些只保留 metadata、哪些不做 embedding、哪些作为文档导航信息保留。

一句话说,PDF 页码范围过滤是有用的兜底能力,但不是稳定的数据质量方案。真正要解决企业级 RAG 的噪声问题,应该做内容级页面分类和结构化抽取,而不是把“第几页”当成“什么内容”的代理。

wolf8334 avatar Jun 10 '26 01:06 wolf8334

I’d be interested in working on a small, focused implementation for this if the maintainers think the API direction is acceptable.

I agree with the point above that page-range filtering should not be presented as a complete enterprise RAG data-cleaning solution. I would frame it only as an optional manual filtering rule for cases where users already know which physical PDF pages they want to include.

A possible narrow scope could be:

  • add a simple page range option to PdfDocumentReaderConfig
  • apply it in PagePdfDocumentReader while preserving the current default behavior
  • add tests for selected ranges and interaction with pagesPerDocument
  • add a short documentation note if needed

Would this direction be acceptable before I start a PR?

fw-coder-tl avatar Jun 12 '26 17:06 fw-coder-tl

Took a shot at this — PR is up at #6445.

Kept it deliberately small: an optional, 1-based page-range filter on PdfDocumentReaderConfig that PagePdfDocumentReader honors. With no ranges set, behavior and output are unchanged. Multiple disjoint ranges are allowed, ranges past the end clamp to the last page, and overlaps are deduped. Added tests for ranges, disjoint ranges, clamping, overlap, pagesPerDocument interaction, and invalid input.

Framed it as a coarse manual filter (skip a known cover/TOC/appendix), not a RAG data-cleaning solution — agreeing with the point @wolf8334 raised above.

@fw-coder-tl you mentioned interest earlier, happy to coordinate or step back. Also open to feedback on the API shape (currently withPageRanges(int[]... ranges); a PageRange type or "3-50,55-100" string would work too).

subhashpolisetti avatar Jun 17 '26 09:06 subhashpolisetti

Thanks for putting this together, @subhashpolisetti. The scope aligns closely with what I had in mind, and I appreciate keeping it as a coarse manual filter rather than presenting it as a complete RAG data-cleaning solution.

No need to step back from my side — I’m happy to collaborate. I’ll review #6445, run the relevant tests locally, and leave concrete feedback on the API shape and edge cases there.

fw-coder-tl avatar Jun 18 '26 03:06 fw-coder-tl