A fast, helpful, and open-source document parser
Merge branch 'main' into pierre/rotation-aware-page-bounds
Logan Markewicha8466f9f3441
diff --cc crates/liteparse/src/extract.rsindex e6f81d2,a3cef4d..c5ae8fc--- a/crates/liteparse/src/extract.rs+++ b/crates/liteparse/src/extract.rs@@@ -113,159 -117,222 +117,227 @@@ pub(crate) fn extract_pages_and_imagesbreak;}- let page = document.page(page_index)?;- let raw_page_width = page.width();- let raw_page_height = page.height();- let view_box = page.view_box().unwrap_or(RectF {- left: 0.0,- top: raw_page_height,- right: raw_page_width,- bottom: 0.0,- });- // All extracted geometry is converted to the rotation-adjusted- // viewport coordinate space. Keep the page dimensions in that same- // space so projection, filtering, and consumers do not clip content- // at the unrotated MediaBox width on /Rotate 90 or /Rotate 270 pages.- let (page_width, page_height) = page.viewport_size(&view_box);- // Once a qualifying widget is found, PDFium flattens every visible- // annotation on the page. Collect every annotation-backed output first.- let links = if extract_links {- page.links(&view_box)- } else {- Vec::new()- };- // Computed when emitted (`extract_content_bounds`) or needed- // internally by the white-fill heuristic (`extract_vector_graphics`).- let content_bounds = (output_options.extract_content_bounds- || output_options.extract_vector_graphics)- .then(|| {- page.content_bounds()- .map(|bounds| rect_from_pdfium(page.bounds_to_viewport(&view_box, &bounds)))- })- .flatten();- let paths = page.path_objects(&view_box);- let graphics = extract_layout_graphics(&paths);- let vector_graphics = output_options- .extract_vector_graphics- .then(|| build_vector_graphics(&paths, content_bounds.as_ref()));- let struct_nodes = extract_page_struct_nodes(&page, &view_box);- let extracted_refs =- extract_page_image_refs(&page, page_number, output_options.extract_images);- let mut image_refs = extracted_refs.refs;- image_error_count += extracted_refs.error_count;- let pdf_annotations = (output_options.extract_annotations- || output_options.extract_structure_tree)- .then(|| page.annotations(&view_box))- .unwrap_or_default();- let annotations = output_options- .extract_annotations- .then(|| pdf_annotations.iter().map(document_annotation).collect());- let structure_tree = output_options.extract_structure_tree.then(|| {- let annotations_by_object = pdf_annotations- .iter()- .filter(|annotation| annotation.subtype == "link")- .filter_map(|annotation| annotation.object_number.map(|n| (n, annotation)))- .collect::<std::collections::HashMap<_, _>>();- StructureTree {- roots: page- .structure_tree()- .into_iter()- .map(|element| structure_tree_element(element, &annotations_by_object))- .collect(),- }- });- let form_fields = output_options.extract_form_fields.then(|| {- form_environment.as_ref().map_or_else(Vec::new, |form| {- page.form_fields(form, &view_box, page_number)- .into_iter()- .map(|field| FormField {- id: field.id,- field_type: field.field_type,- page: field.page,- annotation_index: field.annotation_index,- widget_index: field.widget_index,- object_number: field.object_number,- name: field.name,- alternate_name: field.alternate_name,- value: field.value,- export_value: field.export_value,- field_flags: field.field_flags,- control_count: field.control_count,- control_index: field.control_index,- checked: field.checked,- rect: field.rect.map(rect_from_pdfium),- options: field.options,- selected_options: field.selected_options,- })- .collect()- })- });+ let page_result = extract_single_page(+ document,+ page_index,+ page_number,+ extract_links,+ glyph_resolver,+ &output_options,+ form_environment.as_ref(),+ document_has_form,+ &mut image_cache,+ );- if output_options.extract_images && !image_refs.is_empty() {- let rendered = render_page_images(&page, page_number, &image_refs, &mut image_cache);- image_error_count += rendered.error_count;- images.extend(rendered.images);- for image_ref in &mut image_refs {- image_ref.jpeg_bytes = None;- image_ref.raw_bytes = None;+ match resolve_page_result(+ page_number,+ page_result,+ output_options.continue_on_page_error,+ &mut page_errors,+ )? {+ Some(extraction) => {+ pages.push(extraction.page);+ images.extend(extraction.images);+ image_error_count += extraction.image_error_count;+ flattened_form_widgets |= extraction.flattened_form_widgets;}+ // A failed page's cached renders must not seed dedup for later+ // pages: a hit would emit `duplicate_of` pointing at an image id+ // that never made it into the output.+ None => image_cache.remove_page(page_number),}+ }- // PDFium's text API reads only the page content stream. Filled form- // values commonly live in widget appearance streams, so promote only- // those widget appearances into page content and reload before text- // extraction. Non-widget annotations are excluded, and this does not- // initialize the form environment or execute document JS.- //- // `widget_text_rects` is empty for the overwhelming majority of pages —- // documents with no AcroForm catalog never even reach the annotation- // walk — so the whole path costs one `form_type()` call for most files.- let extract_text = |page: &Page| -> Result<Vec<TextItem>, LiteParseError> {- let text_page = page.text()?;- extract_page_text_items(- page,- &text_page,- &view_box,- glyph_resolver,- output_options.emit_word_boxes,- output_options.extract_text_metadata,- )- };- let widget_text_rects = if document_has_form {- page.form_widget_text_rects(&view_box)- } else {- Vec::new()- };- let mut text_items = if widget_text_rects.is_empty() {- extract_text(&page)?- } else {- // PDFium's text layer keeps only one of two runs that start at- // essentially the same point, so a flattened appearance can- // suppress page text it lands on. Usually widget rects sit over- // blank space, and this bounds-only probe says so without touching- // the text API; only when a widget really does cover existing text- // do we extract twice and put back what was suppressed.- let overlaps_existing_text = page.text_objects_overlap(&view_box, &widget_text_rects);- let before = overlaps_existing_text- .then(|| extract_text(&page))- .transpose()?;- drop(page);- match document.flatten_form_widgets(page_index)? {- Some(flattened_page) => {- flattened_form_widgets = true;- let mut items = extract_text(&flattened_page)?;- if let Some(before) = before {- restore_flattened_over_text(&mut items, before, &widget_text_rects);- }- items+ Ok(ExtractedPages {+ pages,+ page_errors,+ images,+ image_error_count,+ flattened_form_widgets,+ })+ }++ /// Everything one successfully extracted page contributes to the document+ /// output. Accumulated page-locally so a failed page is rolled back by+ /// dropping this value (plus [`ImageCache::remove_page`] for its cache+ /// inserts) instead of undoing shared-state mutations.+ struct PageExtraction {+ page: LitePage,+ /// Rendered image bytes; empty unless `extract_images` was set.+ images: Vec<ExtractedImage>,+ image_error_count: u32,+ /// Whether this page was flattened to recover form-widget text.+ flattened_form_widgets: bool,+ }++ #[allow(clippy::too_many_arguments)]+ fn extract_single_page(+ document: &Document,+ page_index: i32,+ page_number: u32,+ extract_links: bool,+ glyph_resolver: Option<&dyn crate::GlyphResolver>,+ output_options: &ExtractionOutputOptions,+ form_environment: Option<&FormEnvironment<'_, '_>>,+ document_has_form: bool,+ image_cache: &mut ImageCache,+ ) -> Result<PageExtraction, LiteParseError> {+ let mut images = Vec::new();+ let mut image_error_count = 0u32;+ let mut flattened_form_widgets = false;+ let page = document.page(page_index)?;- let page_width = page.width();- let page_height = page.height();++ let raw_page_width = page.width();++ let raw_page_height = page.height();+ let view_box = page.view_box().unwrap_or(RectF {+ left: 0.0,- top: page_height,- right: page_width,++ top: raw_page_height,++ right: raw_page_width,+ bottom: 0.0,+ });++ // All extracted geometry is converted to the rotation-adjusted++ // viewport coordinate space. Keep the page dimensions in that same++ // space so projection, filtering, and consumers do not clip content++ // at the unrotated MediaBox width on /Rotate 90 or /Rotate 270 pages.++ let (page_width, page_height) = page.viewport_size(&view_box);+ // Once a qualifying widget is found, PDFium flattens every visible+ // annotation on the page. Collect every annotation-backed output first.+ let links = if extract_links {+ page.links(&view_box)+ } else {+ Vec::new()+ };+ // Computed when emitted (`extract_content_bounds`) or needed+ // internally by the white-fill heuristic (`extract_vector_graphics`).+ let content_bounds = (output_options.extract_content_bounds+ || output_options.extract_vector_graphics)+ .then(|| {+ page.content_bounds()+ .map(|bounds| rect_from_pdfium(page.bounds_to_viewport(&view_box, &bounds)))+ })+ .flatten();+ let paths = page.path_objects(&view_box);+ let graphics = extract_layout_graphics(&paths);+ let vector_graphics = output_options+ .extract_vector_graphics+ .then(|| build_vector_graphics(&paths, content_bounds.as_ref()));+ let struct_nodes = extract_page_struct_nodes(&page, &view_box);+ let extracted_refs = extract_page_image_refs(&page, page_number, output_options.extract_images);+ let mut image_refs = extracted_refs.refs;+ image_error_count += extracted_refs.error_count;+ let pdf_annotations = (output_options.extract_annotations+ || output_options.extract_structure_tree)+ .then(|| page.annotations(&view_box))+ .unwrap_or_default();+ let annotations = output_options+ .extract_annotations+ .then(|| pdf_annotations.iter().map(document_annotation).collect());+ let structure_tree = output_options.extract_structure_tree.then(|| {+ let annotations_by_object = pdf_annotations+ .iter()+ .filter(|annotation| annotation.subtype == "link")+ .filter_map(|annotation| annotation.object_number.map(|n| (n, annotation)))+ .collect::<std::collections::HashMap<_, _>>();+ StructureTree {+ roots: page+ .structure_tree()+ .into_iter()+ .map(|element| structure_tree_element(element, &annotations_by_object))+ .collect(),+ }+ });+ let form_fields = output_options.extract_form_fields.then(|| {+ form_environment.map_or_else(Vec::new, |form| {+ page.form_fields(form, &view_box, page_number)+ .into_iter()+ .map(|field| FormField {+ id: field.id,+ field_type: field.field_type,+ page: field.page,+ annotation_index: field.annotation_index,+ widget_index: field.widget_index,+ object_number: field.object_number,+ name: field.name,+ alternate_name: field.alternate_name,+ value: field.value,+ export_value: field.export_value,+ field_flags: field.field_flags,+ control_count: field.control_count,+ control_index: field.control_index,+ checked: field.checked,+ rect: field.rect.map(rect_from_pdfium),+ options: field.options,+ selected_options: field.selected_options,+ })+ .collect()+ })+ });++ if output_options.extract_images && !image_refs.is_empty() {+ let rendered = render_page_images(&page, page_number, &image_refs, image_cache);+ image_error_count += rendered.error_count;+ images.extend(rendered.images);+ for image_ref in &mut image_refs {+ image_ref.jpeg_bytes = None;+ image_ref.raw_bytes = None;+ }+ }++ // PDFium's text API reads only the page content stream. Filled form+ // values commonly live in widget appearance streams, so promote only+ // those widget appearances into page content and reload before text+ // extraction. Non-widget annotations are excluded, and this does not+ // initialize the form environment or execute document JS.+ //+ // `widget_text_rects` is empty for the overwhelming majority of pages —+ // documents with no AcroForm catalog never even reach the annotation+ // walk — so the whole path costs one `form_type()` call for most files.+ let extract_text = |page: &Page| -> Result<Vec<TextItem>, LiteParseError> {+ let text_page = page.text()?;+ extract_page_text_items(+ page,+ &text_page,+ &view_box,+ glyph_resolver,+ output_options.emit_word_boxes,+ output_options.extract_text_metadata,+ )+ };+ let widget_text_rects = if document_has_form {+ page.form_widget_text_rects(&view_box)+ } else {+ Vec::new()+ };+ let mut text_items = if widget_text_rects.is_empty() {+ extract_text(&page)?+ } else {+ // PDFium's text layer keeps only one of two runs that start at+ // essentially the same point, so a flattened appearance can+ // suppress page text it lands on. Usually widget rects sit over+ // blank space, and this bounds-only probe says so without touching+ // the text API; only when a widget really does cover existing text+ // do we extract twice and put back what was suppressed.+ let overlaps_existing_text = page.text_objects_overlap(&view_box, &widget_text_rects);+ let before = overlaps_existing_text+ .then(|| extract_text(&page))+ .transpose()?;+ drop(page);+ match document.flatten_form_widgets(page_index)? {+ Some(flattened_page) => {+ flattened_form_widgets = true;+ let mut items = extract_text(&flattened_page)?;+ if let Some(before) = before {+ restore_flattened_over_text(&mut items, before, &widget_text_rects);}- None => extract_text(&document.page(page_index)?)?,+ items}- };- assign_links(&mut text_items, &links);- assign_strikethrough(&mut text_items, &graphics);+ None => extract_text(&document.page(page_index)?)?,+ }+ };+ assign_links(&mut text_items, &links);+ assign_strikethrough(&mut text_items, &graphics);- pages.push(LitePage {+ Ok(PageExtraction {+ page: LitePage {page_number: page_number as usize,page_width,page_height,