PDF parsing

An amount in the PDF—how can its position on the page be retrieved?

appears twice in a single statement 1,200.00: once in the payable amount field, and once in the description text. A full-text search can locate both, but it can

阅读文本 / Reading text
This paper uses synthetic samples to demonstrate the processing method. The code has been verified using examples in an isolated environment; this does not guarantee effectiveness for all real files or products. Before processing important files, please retain the original copies and verify them against the boundaries and acceptance criteria outlined in this document. appears twice in a single statement 1,200.00 : once in the payable amount field, and once in the description text. A full-text search can locate both, but it cannot determine for you which one is the business field. Simply taking the first match is a hard-to-detect error—resulting in an amount that appears correct, yet the source has already been compromised. If the layout of this form is fixed, first define a known region and then search for text; this approach is often easier to interpret than continuing to add regular expressions. The key is not merely “finding only one box,” but treating both zero matches and multiple matches as explicit results, so that the program does not arbitrarily make choices on behalf of the business. retains the position of the word, rather than merely retaining the text PyMuPDF's page.get_text("words") returns a word record with position information. Common fields include (x0, y0, x1, y1, text, block_no, line_no, word_no) . The following example extracts only the first five fields, while the last three identifiers are temporarily excluded from the region filtering. Here, the term is a fragment provided by the extractor; it does not necessarily correspond to a word in the linguistic sense, nor does it guarantee that an amount will always constitute a complete fragment. 1,200.00 may be split apart or may carry adjacent tags. This paper addresses only exact matches of complete segments: it is preferable to forward records that do not meet the criteria for revalidation rather than silently concatenating them into a seemingly valid amount. Two composite pages with the same amount We create a new PDF page in memory and place the same amount near the vertical coordinates 120 and 420. The query region covers only the amount above. The text insertion point is at the baseline, not at the top-left corner of the text box; since the actual height and width of the box depend on the font and font size, we cannot hard-code the coordinates as “necessarily equal to a specific value.” ’s correct output should satisfy two conditions: there is only one candidate, and the candidate rectangle is completely contained within the query region. Subsequently, when the query range is expanded to cover the entire page, two candidates should be obtained, thereby triggering the ambiguity branch. Finally, a string that does not appear on the page is used to verify zero hits. This approach more closely aligns with the contract required by the actual interface than merely demonstrating a single successful lookup. executable code: Pass the candidate quantity to the caller dependency is pymupdf , please install it in the test environment and lock the version. The following will not access the network, write files, or modify existing customer documents. It generates only a PDF for demonstration purposes. import pymupdf def locate(page, target, query): query = pymupdf.Rect(query) candidates = [] for word in page.get_text("words"): x0, y0, x1, y1, text = word[:5] box = pymupdf.Rect(x0, y0, x1, y1) if text == target and query.contains(box): candidates.append(tuple(box)) return candidates def decide(candidates): if len(candidates) == 0: return "missing" if len(candidates) > 1: return "ambiguous" return "unique" with pymupdf.open() as doc: page = doc.new_page(width=595, height=842) page.insert_text((80, 120), "1,200.00", fontsize=11) page.insert_text((80, 420), "1,200.00", fontsize=11) query = pymupdf.Rect(72, 100, 300, 150) local = locate(page, "1,200.00", query) assert decide(local) == "unique" assert query.contains(pymupdf.Rect(local[0])) assert decide(locate(page, "1,200.00", page.rect)) == "ambiguous" assert decide(locate(page, "999.99", query)) == "missing" print("unique / ambiguous / missing cases passed") contains must fully encompass the target area, rather than merely touching its edges. If the query box is too tight, amounts near the border may fall into the zero-hit range; this is not a valid reason to automatically expand it to cover the entire page. First verify the coordinate system you used when defining the measurement area, then decide whether to adjust the range accordingly. If the business logic indeed permits the center point to be within the boundary, you should write a separate rule and conduct additional tests for boundary overlaps—do not subtly alter the intended meaning within the same function. three outcomes, three processing methods result possible causes Suggested action uniquely matches There is only one fully matching fragment within the region. stores the page number, original text, rectangle, and rule version zero hits area is invalid, the amount has been split, and the text layer is missing Mark the reason candidates, check the original page, and do not pad with zeros. multiple hits There are duplicate amounts in the same region, or the template has changed returns all candidates, combined with tags or manual disambiguation has a frame but the value is incorrect The text layer itself is erroneous, or the matching target is incorrect returns to the original page for verification, ensuring that coordinate substitution values are not endorsed box appears offset from displays coordinates and extracts coordinates in a mixed manner explicitly defines the transformation chain for rotation, cropping, and rendering scaling production logic should not rely solely on assert intercepts exceptions because optimization modes may remove assertions. In the example, it is used for regression checks; when actually enqueuing tasks, explicit conditional branches and business states should be employed. This is not a general-purpose amount extractor code does not parse currency, thousand separators, or decimal rules, nor does it recognize the semantics of “current period payable” versus “prior period balance.” The candidate is unique, but this does not equate to uniqueness in business meaning. Scanned documents must first extract usable text and its spatial coordinates; pages with a text layer but containing erroneous content cannot be approved simply because they are “copyable.” This paper uses unrotated composite pages. When real pages are rotated, it is necessary first to specify whether the query box originates from the display screen or from extracted coordinates, and to perform conversion if needed; do not simply multiply by a matrix without distinguishing the source. When saving the source page, also differentiate between zero-based indexing and human‑oriented page numbers, so that reviewers do not mistakenly conclude that evidence is absent after opening adjacent pages. leaves the key numbers for post-translation review Document translation involves more than just ensuring sentence fluency; key elements such as amounts, dates, and quantities must also be verified item by item. OmniDoc (Product Entry) provides multiple entry points for document translation, and the bilingual comparison featured on the official website can serve as a verification reference; the coordinate-locating script, on the other hand, is suitable for preserving original-text evidence and helping to pinpoint problematic areas. is first evaluated using desensitized samples that have upload permissions. After the translation becomes longer, the content’s position may reasonably shift; therefore, one should not treat “the new and old coordinates being exactly the same” as an absolute criterion for correct translation. A more valuable check is whether the amounts are preserved, the currency is clearly specified, and the corresponding tags still point to the same business meaning. With a clear division of labor between technical checks and manual review, this approach provides far greater assistance in delivery than any single claim of “complete fidelity.” Next, save a set of failed samples Identify the zero-hit and multi-hit pages in your actual template, document the reasons for each separately, and then decide whether to supplement regional rules, add tag constraints, or switch to another extraction route. Do not use an arbitrarily set percentage to determine switching conditions across all business cases. interface field reference: PyMuPDF Page.get_text . The synthesis examples in this paper do not represent the accuracy testing of real invoices. - 1 -
Updated 2026-10-08