A method and device for repairing a damaged PDF file

By using binary scanning slicing and adaptive repair logic, the problem of low success rate in repairing complex and damaged PDF files in existing technologies has been solved, achieving automated repair and improved stability, while ensuring the format standardization and compatibility of PDF files.

CN123157673APending Publication Date: 2026-11-24INST OF SOFTWARE - CHINESE ACAD OF SCI
View PDF 0 Cites 0 Cited by

Patent Information

Application Number
CN202611323221.1
Authority / Receiving Office
CN · China
Patent Type
Applications(China)
Current Assignee / Owner
Filing Date
2026-08-28
Publication Date
2026-11-24

AI Technical Summary

Technical Problem

Existing PDF repair technologies have low success rates, cannot restore resources, and have poor fault tolerance when faced with complex damage scenarios, failing to meet the high integrity and high stability requirements of government archiving and enterprise office work.

Method used

The PDF is split into independent objects by binary scanning slicing, the streaming data type is identified, adaptation and repair logic is executed, page collection objects and cross-reference tables are established, and an exception tolerance mechanism is set up to ensure the stability and integrity of the repair process.

Benefits of technology

It enables automated repair of various structurally damaged PDF files, improving the success rate of repair, ensuring the format standardization and cross-platform compatibility of the repaired PDF files, and avoiding complete file corruption during the repair process.

✦ Generated by Eureka AI based on patent content.

Smart Images

  • Figure CN123157673A_ABST
    Figure CN123157673A_ABST
Patent Text Reader

Abstract

This invention provides a method and apparatus for repairing damaged PDF files. The method includes: reading the binary data stream of the damaged PDF to be repaired, and obtaining several ordered PDF data fragments through parsing; parsing each PDF data fragment one by one, and executing corresponding repair logic for object streams, compressed encoded streams, and ordinary dictionary objects according to the different stream identifier types carried by the data fragments, completing the parsing and repair of all valid PDF objects; traversing the repaired PDF objects, filtering valid page objects and establishing a page collection object to aggregate document page resources; creating a PDF directory object, binding the page collection object, and configuring cross-reference table parameters to complete the establishment of the top-level structure of the PDF file; capturing runtime anomalies in real time during the overall repair process, and finally encapsulating the constructed PDF structure data into a binary file and outputting the repaired PDF file. This invention can effectively improve the integrity and stability of repairing damaged PDF files.
Need to check novelty before this filing date? Find Prior Art

Description

Technical Field

[0001] This invention belongs to the field of document data restoration technology, specifically relating to a method and apparatus for repairing damaged PDF files. Addressing the challenge of repairing structurally damaged PDF files, this invention proposes an automated, highly fault-tolerant PDF repair solution, adaptable to various scenarios involving the restoration and repair of damaged PDF files. Background Technology

[0002] PDF (Portable Document Format) is currently the most widely used static document format in office, publishing, government archiving, and data transmission scenarios. Its official international standard is ISO 32000, which specifies that a PDF file consists of four parts: a header, body objects, a cross-reference table, and a footer. It features a fixed layout, cross-platform compatibility, and strong resource encapsulation. The PDF file body is composed of several independent dictionary objects, stream objects, and nested page objects, supporting DEFLATE lossless compression encoding for lightweight resource storage. However, during PDF file transmission, storage, compression, abnormal power outages, program crashes, malicious tampering, and fragmented storage, compliance failures such as lost body objects, invalid cross-reference tables, broken object stream nesting, compression encoding / decoding failures, and broken page object indexes can easily occur. These failures can prevent PDF readers from parsing the file correctly, resulting in issues such as documents that cannot be opened, blank documents, missing pages, and missing text and image resources, making it impossible to read important office documents and archived files.

[0003] Most existing PDF repair technologies rely on commercial readers or general document repair tools, with relatively simple repair logic and a failure to adhere to PDF structure specifications. Traditional repair solutions typically only address simple faults such as corrupted file headers or missing file footers. For complex damage scenarios involving deep PDF structures, such as invalid cross-reference tables, broken nested / ObjStm object streams, abnormal DEFLATE lossless compression encoding / decoding, scattered or missing page objects, and corrupted multi-level nested dictionary objects, the success rate is extremely low, and the PDF structure cannot be restored.

[0004] Meanwhile, existing technologies have significant technical shortcomings: First, they cannot separate independent dictionary objects and stream objects in PDFs, making it difficult to identify valid discrete object data in damaged files, resulting in the direct discarding of a large number of underlying image and text objects; Second, they do not distinguish between / ObjStm object streams, / FlateDecode compressed streams, and ordinary dictionary objects, lacking layered adaptation and repair logic, and are unable to decompress and restore damaged compressed resources and nested sub-objects; Third, most repair tools do not establish Catalog directory objects, Pages page collection objects, and cross-reference top-level structures, but simply splice together residual data, resulting in PDFs with layout errors, missing pages, and inability to be opened normally; Fourth, traditional solutions have poor fault tolerance, and once a parsing error occurs during the repair process, the repair task will be terminated directly, leading to complete file corruption, with no fallback repair mechanism.

[0005] In summary, existing PDF repair technologies suffer from limitations such as limited adaptability to specific scenarios, weak ability to repair complex damaged PDFs, incomplete structural design, and poor fault tolerance. These shortcomings prevent them from meeting the high integrity and stability requirements for repairing damaged PDFs in scenarios such as government archiving, enterprise office work, and document archiving. Summary of the Invention

[0006] The purpose of this invention is to overcome the shortcomings of the prior art and provide a method and apparatus for repairing damaged PDF files. This invention solves the technical problems of low success rate, inability to restore resources, poor fault tolerance, and loss of page resources in the repair of complex damaged PDFs. It enables automated repair of various structurally damaged PDF files and improves the integrity and compatibility of PDF repair.

[0007] To achieve the above objectives, the first aspect of the present invention provides a method for repairing damaged PDF files, comprising the following steps: Read the binary data stream of the damaged PDF to be repaired, scan and parse the binary data stream of the PDF, identify the start and end positions of all objects in the PDF file, and divide it into several independent PDF data segments; Each PDF data fragment is parsed and processed one by one to identify the stream data type within the PDF data fragment. Adaptive repair logic is executed for object streams, compressed decoding streams, and ordinary text objects respectively to restore the underlying object data of the damaged PDF. Iterate through all repaired PDF objects, filter all page objects, count the number of page objects and construct a page collection object, and associate all page objects; Create a PDF directory object, bind the page collection object to the PDF directory object, configure the PDF file root directory identifier and cross-reference table size parameters, and establish a complete PDF file structure; The completed PDF file structure is packaged into a standard PDF binary file to complete the repair of damaged PDF files; Extract the text content and image resources from the repaired PDF file, verify the integrity of the PDF page resources, and complete the file repair verification.

[0008] Further, the PDF data fragment is obtained using the following steps: The PDF binary data stream is scanned using regular expression matching to match the start and end identifiers of PDF objects, marking the start and end offset positions of each PDF object. Based on the identifier matching results, the PDF data stream is sliced ​​to generate PDF data fragments carrying object numbers, start offsets, and end offsets, and all PDF data fragments are sorted according to object numbers.

[0009] Furthermore, the adaptation and repair logic executed for object streams, compressed / decoded streams, and plain text objects respectively includes: Extract the binary data of a single PDF data segment, match the start and end markers of the stream within the segment, and locate the stream data range of the PDF object; If the PDF data fragment contains an object stream identifier, the object stream is decompressed using the DEFLATE lossless compression and decompression algorithm, the object stream header parameters are parsed, multiple nested sub-objects within the object stream are split, and all sub-object data is repaired and written in batches. If the data fragment contains a PDF Flate compression encoding identifier, the compressed stream data is decompressed, the PDF object description text is retained, and the original stream data corresponding to the object is updated. If no valid stream data is available, the fragment text data is read directly to complete the repair and writing of the ordinary PDF object.

[0010] Furthermore, the process of traversing all repaired PDF objects, filtering all page objects, counting the number of page objects and constructing a page collection object, and associating all page objects includes: Iterate through all objects in the PDF file cross-reference table, identify PDF page objects of type "page", and summarize all valid page objects; create a new page collection object, associate all page objects with the child nodes of the page collection object, count the total number of pages, and write the count parameter of the page collection object.

[0011] Furthermore, the step of creating a PDF directory object, binding the page collection object to the PDF directory object, configuring the PDF file root directory identifier and cross-reference table size parameters, and establishing a complete PDF file structure includes: Create a PDF directory object and bind the page collection object to the directory root object; modify the root node parameter of the PDF file cross-reference table to point the root node to the directory root object, and configure the cross-reference table size according to the maximum object number to repair the top-level structure of the PDF file.

[0012] Furthermore, anomalies are captured in real time during the repair process. When an anomaly occurs in the PDF structure creation, a repair file is directly generated based on the original parsed PDF object data, thus avoiding file repair failure.

[0013] A second aspect of the present invention provides a damaged PDF file repair apparatus for performing the damaged PDF file repair method described in any of the preceding claims, comprising: The data reading module is used to read the binary data stream of the damaged PDF to be repaired, and input the original data of the damaged PDF; The fragment splitting module is used to scan the PDF binary data stream, identify the start and end markers of PDF objects, and split the data into several ordered PDF data fragments. The object repair module, connected to the fragment splitting module, is used to parse PDF data fragments one by one, identify streaming data types, complete object stream decompression, nested sub-object splitting, compressed data decoding, and repair various basic PDF objects. The page creation module, connected to the object repair module, is used to filter PDF page objects, construct page collection objects, and summarize and associate all page resources. The structure creation module, connected to the page creation module, is used to create PDF directory objects, bind page collections, configure PDF root directory and cross-reference table parameters, and establish the PDF file structure. The file generation module, connected to the structure establishment module, is used to encapsulate the established PDF file structure into a standard PDF binary file and output the repaired PDF file. An exception handling module is used to capture program exceptions during the repair process and generate a repair file based on the original parsed data when the PDF file structure fails to be built. The resource detection module is used to extract page text and page image resources from the repaired PDF file and verify the integrity of the PDF file resources.

[0014] Furthermore, the object repair module includes: The marker positioning unit is used to match the start and end markers of the stream within a PDF data segment to accurately locate the stream data interval; The object stream parsing unit is used to identify object stream identifiers and to split, traverse, and batch repair and write nested sub-objects. The compression decoding unit is used to identify the PDF Flate compression encoding identifier, decompress the compressed stream data using the DEFLATE lossless compression standard decoding algorithm, and update the PDF object resource data.

[0015] Compared with the prior art, the present invention has the following beneficial effects: 1. This invention splits PDF independent objects by binary scanning slicing and breaks disordered damaged data streams, which can extract discrete and incomplete valid object data from damaged PDFs, improve the problem of missing valid data in traditional repair methods, and improve the utilization rate of damaged data.

[0016] 2. This invention verifies the validity of nested syntax in PDF dictionaries, automatically filters out interference from comments and escape characters, removes invalid objects with broken syntax, and combines the DEFLATE lossless compression decoding algorithm and batch fragment parsing algorithm with layered adaptation and repair logic for / ObjStm object streams, / FlateDecode compressed encoding streams, and ordinary dictionary objects to adapt to various complex structural damage scenarios.

[0017] 3. This invention establishes a top-level structure of page object collection, Catalog directory root object, and cross-reference table, repairing the problems of missing top-level structure and index failure in PDF, ensuring that the repaired PDF file format is standardized, and improving the compatibility of readers across all platforms.

[0018] 4. This invention sets up an anomaly tolerance fallback mechanism, which can generate a repair file based on the original parsed data when the structure is abnormal, avoiding the complete corruption of the file due to errors in the repair process and improving the stability of the repair.

[0019] 5. This invention adds a post-repair resource verification mechanism to verify the integrity of page text and image resources, ensuring the availability and integrity of the repaired PDF file. Attached Figure Description

[0020] To more clearly illustrate the technical solutions of the embodiments of the present invention, the accompanying drawings used in the embodiments will be briefly described below. These drawings are incorporated in and constitute a part of this specification. They illustrate embodiments conforming to the present invention and, together with the specification, serve to explain the technical solutions of the present invention. It should be understood that the following drawings only show some embodiments of the present invention and should not be considered as a limitation of the scope. For those skilled in the art, other related drawings can be obtained from these drawings without creative effort.

[0021] Figure 1 This is a schematic diagram of the overall process of the method for repairing damaged PDF files provided in an embodiment of the present invention; Figure 2 This is a schematic diagram of the specific process of S20 in the damaged PDF file repair method provided in the embodiments of the present invention; Figure 3 This is a flowchart illustrating the BE pairwise matching sharding algorithm defined in an embodiment of the present invention. Figure 4 A flowchart illustrating the PDF syntax balance verification algorithm defined in an embodiment of the present invention; Figure 5 The diagram shows a schematic representation of the device structure provided in some embodiments of the present invention. Detailed Implementation

[0022] To make the objectives, technical solutions, and advantages of this invention clearer, the invention will be further described in detail below with reference to the accompanying drawings and embodiments. It should be understood that the specific embodiments described herein are merely illustrative and not intended to limit the invention. Furthermore, the technical features involved in the various embodiments of this invention described below can be combined with each other as long as they do not conflict with each other.

[0023] In this invention, the terms "first," "second," etc. (if present) in the invention and the accompanying drawings are used to distinguish similar objects and are not necessarily used to describe a specific order or sequence.

[0024] Before providing a detailed description of the technical solution of this invention, the PDF-specific identifiers and field concepts involved in this invention are explained in a unified manner. The following identifiers, fields, and definitions all conform to the ISO 32000 standard, and those skilled in the art can clearly understand the corresponding technical meanings based on the ISO 32000 international standard: obj and endobj: These are object boundary identifiers in a PDF file. obj is used to mark the start position of a single PDF dictionary object, and endobj is used to mark the end position of a single PDF dictionary object. The two identifiers appear in pairs to define the data range of independent objects.

[0025] / ObjStm: This is a PDF object stream marker, belonging to a special dictionary object type. It is used to nest and store multiple sub-dictionary objects in a single stream structure, and is often used to compress and store a large number of small resource objects.

[0026] / FlateDecode: This is a standard PDF compression filter identifier used to indicate that the current object stream is encoded using DEFLATE compression. When the file is corrupted, decompression failure and resource data loss often occur.

[0027] DEFLATE: A general lossless compression algorithm for PDFs, combining the LZ77 algorithm with Huffman coding to compress binary resources, used to reduce the storage size of PDF images, text, fonts, and form resources.

[0028] Catalog: The root object of the PDF directory, serving as the top-level index object of the PDF file. It is used to associate page collection objects and is the core structure that allows PDF files to be recognized by readers.

[0029] Pages: A collection of PDF pages, used to uniformly organize all page objects within a document and centrally manage page layout and relationships.

[0030] Root: This is the root node parameter for the PDF cross-reference table, pointing to the root object of the Catalog directory, defining the top-level structure entry point of the PDF file.

[0031] Size: This is the size parameter of the PDF cross-reference table, used to record the largest object number in the current PDF file, representing the data size of the cross-reference table.

[0032] Count: This is a field for counting the number of pages in the current document. It is configured within the Pages object and is used to record the total number of valid pages in the current document.

[0033] Type: This is the type identifier for the PDF dictionary object, used to define the specific type of the current dictionary object and distinguish different structural attributes such as page objects, directory objects, and resource objects.

[0034] / Page: This is a page type identifier, assigned to the Type field, used to mark the current dictionary object as an independent document page object.

[0035] Kids: A list field for child nodes of the Pages object, used to store the IDs of all subordinate page objects, enabling batch association and aggregation of page resources.

[0036] Based on the above standard field definitions, this invention fully realizes layered parsing, syntax verification, layered repair, and structure establishment of damaged PDFs.

[0037] In one embodiment of the present invention, a method for repairing damaged PDF files is provided, such as... Figure 1 As shown, it includes the following steps: S10. Data Slicing and Parsing. The damaged PDF binary data stream to be repaired is read, and the stream is scanned and parsed to identify the start and end positions of all objects in the PDF file, dividing it into several independent PDF data segments. The PDF binary data stream is scanned again, matching the start identifier of the `obj` object with the end identifier of `endobj`, marking the start and end offset positions of each PDF dictionary object. Based on the identifier matching results, the PDF data stream is sliced ​​to generate PDF data segments carrying object numbers, start offsets, and end offset attributes. All PDF data segments are then sorted in ascending order according to object numbers, completely preserving valid object data.

[0038] S20. Layered Object Repair. Each PDF data fragment is parsed and processed individually, verifying the object's syntax validity, identifying the stream data type within the data fragment, and executing adaptation and repair logic for object streams, compressed / decoded streams, and plain text objects respectively, to restore the underlying object data of the damaged PDF. Specifically, this includes: S21. Extract the binary data of a single PDF data segment, match the start and end markers of the stream within the segment, and locate the stream data range of the PDF object; S22. If the data fragment contains the / ObjStm object stream identifier, the object stream is decompressed using the DEFLATE lossless compression and decompression algorithm. Based on the First header offset parameter of the parsed object stream, multiple nested sub-dictionary objects within the object stream are split, and all sub-object data is created and written in batches to restore the PDF nested object structure. S23. If the data fragment contains PDF / FlateDecode compression encoding identifiers, decompress the compressed stream data based on the DEFLATE lossless compression decoding rules, fully preserve the PDF object dictionary description text, update the original resource stream data corresponding to the object, and repair the compressed and damaged image and text resources. S24. If there is no valid stream data, check the syntactic integrity of the object. If the syntactic integrity is valid, directly read the fragment text data and complete the repair and writing of the ordinary PDF object. If the syntactic integrity is abnormal, discard the damaged object.

[0039] S30. Page Resource Creation. Iterate through the cross-reference table of all repaired PDF objects, filter all page type objects, count the number of page objects, and create a page collection object, associating all page objects. Specifically, it iterates through all objects in the PDF file cross-reference table, identifies page objects with the Type attribute " / Page," and removes damaged or formatted invalid objects. A new Pages page collection object is created, all valid page objects are associated with the Kids child node list of the page collection object, and the total number of valid pages is counted and assigned to the Count field, thus aggregating page resources.

[0040] S40. Top-level structure establishment. Create a PDF directory object, bind the page collection object to the PDF directory object, configure the PDF file root directory identifier and cross-reference table size parameters, and establish a complete PDF file structure; specifically, create a Catalog directory root object, bind the page collection object to the Pages field of the directory root object; modify the Root node parameter of the PDF global cross-reference table so that the root node points to the newly created directory root object, and configure the cross-reference table Size parameter according to the current largest object number to complete the missing index structure of the PDF top level and repair file structural faults.

[0041] S50, Error Tolerance and File Output. The system encapsulates the completed PDF structure data into a binary PDF file to repair damaged PDF files. During the repair process, errors are captured in real time. When an error occurs during PDF structure creation, a repair file is directly encapsulated based on the original parsed PDF object data to prevent repair failure.

[0042] In one embodiment, step S30 specifically includes: traversing all objects in the PDF file cross-reference table, identifying page objects with the Type attribute as / Page, and removing invalid objects that are damaged or have abnormal formats; creating a new Pages page collection object, associating all valid page objects with the Kids child node list of the page collection object, and counting the total number of valid pages, assigning the value to the Count field, and aggregating page resources.

[0043] In one embodiment, step S40 specifically includes: creating a Catalog root object, binding the page collection object to the Pages field of the catalog root object; modifying the Root node parameter of the PDF global cross-reference table so that the root node points to the newly created catalog root object, and configuring the cross-reference table Size parameter according to the current maximum object number to complete the missing top-level index structure of the PDF and repair file structural faults.

[0044] In one embodiment, the above method captures anomalies in real time during the repair process. When an anomaly occurs in the PDF structure creation, a repair file is directly generated based on the original parsed PDF object data to avoid file repair failure.

[0045] In one embodiment, after the repair is completed, the present invention can additionally perform a resource integrity verification: extract the text content and image resources of the repaired PDF file, verify the integrity of the PDF page resources, and complete the file repair verification. This step is not part of the main repair process and is used to improve the reliability of the repair.

[0046] In one embodiment of the present invention, a method for repairing damaged PDF files is provided, comprising the following steps: S10. Data Slicing and Parsing. Read the original binary data stream of the damaged PDF, complete the global scan slicing, and split it into multiple PDF data fragments carrying unique object numbers and start / end offset parameters. Sort these fragments in ascending order by object number, preserving all valid residual data in the damaged file. The BE pairwise matching slicing algorithm is subordinate to this step, and its execution logic is detailed as follows: Figure 2 As shown, it includes the following steps: S101. Global Identifier Scan Markers. Perform a global regular expression scan on the complete PDF binary data stream, matching the object start feature identifier of "number + obj", marking it as type B, and simultaneously recording the unique number of the current object and the start offset position of the data stream; at the same time, scan all "endobj" object end identifiers in the data stream, marking them as type E, and recording the end offset position. After traversal, summarize all B and E marker point data.

[0047] S102. Global sorting of markers. All B and E markers obtained from the scan are rearranged in ascending order according to the physical offset position of the data stream to restore the true arrangement order of object markers in the damaged data stream and fix the problems of marker disorder and reversed order.

[0048] S103, BE identifier pair matching. Extract all identifier types after sorting, concatenate to generate identifier strings, and use regular expressions to match consecutive "B+E" combinations to determine if a set of consecutive corresponding start and end identifiers constitutes the complete boundary of a single PDF object, filtering out incomplete and invalid segments without matching identifiers.

[0049] S104. Object Fragment Generation and Sorting. Based on the successfully matched BE identifier pairs, extract the binary data of the corresponding offset interval to generate independent PDF object fragments and bind them with the corresponding unique object IDs; after all fragments are sliced, sort all fragments in ascending order according to the object number, and output a well-organized and independently parsable list of PDF object fragments.

[0050] The logic of steps S101-S104 above is the BE pairwise matching and sharding algorithm.

[0051] S20, Layered Object Repair. Each sorted PDF data segment is parsed individually, matching the start and endstream markers within the segment to precisely define the data stream intervals. This step employs a PDF syntax balance check algorithm, subordinate to step S20, to verify the object's syntax validity. It also differentiates between different stream identifier types and executes corresponding repair logic, such as... Figure 3 As shown, it specifically includes sub-steps S21 to S24: S21. Stream Interval Location and Syntax Pre-validation. Traverse the binary data of a single PDF data segment, using regular expressions to match the start and end line breaks of the stream (excluding the endstream suffix) to accurately locate the internal stream data interval of the object. For ordinary objects without a valid stream structure, call the PDF syntax balance validation algorithm to perform syntax validity verification. The algorithm's detailed execution logic is as follows: Figure 4 As shown, it includes the following steps: S211. Parameter initialization. Define a square bracket counter and a dictionary angle bracket opening / closing counter, both initialized to 0, to count the number of openings and closings of various nested symbols; initialize the traversal pointer to traverse character by character starting from the first character of the object string.

[0052] S212. Comment filtering. If a percent sign (the start character of a comment) is detected during the traversal, the subsequent content is determined to be a single-line comment. The position of the newline character in the current line is directly retrieved, and the traversal pointer is jumped to the next position after the newline character, skipping the entire line of comment content and avoiding interference from special symbols in comments on syntax verification.

[0053] S213. Parentheses Nesting Depth Validation. If a left parenthesis is detected, start nesting depth statistics and initialize the depth variable to 1; continue traversing forward. If an escaped backslash is detected, skip the next character and ignore the escape character; if a nested left parenthesis is detected, increment the depth variable; if a right parenthesis is detected, decrement the depth variable; continue traversing until the depth variable reaches zero, completing the multi-level parentheses nesting closure validation. If the depth does not reach zero after traversal, a syntax error is directly determined.

[0054] S214. Dictionary angle bracket validity check. If two consecutive left angle brackets are detected, it is determined as a dictionary open indicator, and the dictionary open counter is incremented; if two consecutive right angle brackets are detected, it is determined as a dictionary close indicator, and the dictionary close counter is incremented; if a single right angle bracket appears, it is determined as illegal syntax, and the object is directly determined to be corrupted. For single-sided angle bracket indicators, if no corresponding closing symbol is found, the syntax is determined to be invalid.

[0055] S215, Bracket Balance Check. During traversal, the open and closed status of brackets is counted in real time. The counter is incremented by one for each identified left bracket and decremented by one for each identified right bracket. If the counter is negative, it means that there are more closed brackets than open brackets, indicating nesting disorder, and a syntax imbalance is directly determined.

[0056] S216. Result Determination and Output. After completing the full character traversal, check whether the square bracket counter and the dictionary angle bracket opening and closing counter are all zeroed. If any type of counter is not zeroed, it is determined that the current PDF object has a broken nested syntax or invalid data, and the object is removed; if all are zeroed, the object is determined to have a valid syntax and can participate in subsequent repairs.

[0057] The logic of steps S211-S216 above constitutes the PDF syntax balance verification algorithm.

[0058] S22. Object Stream Specific Repair. If the data fragment contains the / ObjStm object stream identifier, extract the object dictionary header data, perform DEFLATE lossless decompression on the stream interval data; read the object First header offset parameter, split the object stream header index sequence, divide the nested sub-object intervals by batch pairwise sharding, parse the data of each sub-object interval one by one, create sub-objects in batches and write the parsed data, capture parsing exceptions and automatically skip corrupted sub-objects, and completely restore the multi-level nested object structure of the PDF.

[0059] S23. Special repair for compressed encoded streams. If the data fragment contains the / FlateDecode compression identifier, retain the complete object dictionary header text, perform DEFLATE lossless decoding and decompression on the stream data; create the corresponding PDF object, write the original dictionary information, and update the bound decompressed resource stream data to repair the compressed and damaged image, font, and form resources.

[0060] S24. Repairing ordinary dictionary objects. If there is no valid stream structure, create a blank PDF object. Prioritize parsing the fragment text using UTF-8 encoding. If the syntax check passes, write the object data. If UTF-8 decoding fails, switch to latin-1 encoding for secondary parsing. If the syntax is valid, complete the object writing. If both decoding attempts or syntax check fail, discard the corrupted object.

[0061] S30. Page Resource Creation. Iterate through the cross-reference table of all repaired PDF objects, filter for valid page objects with the Type attribute " / Page", and remove damaged or invalid objects. Create a new Pages collection object, associate all valid page objects with the Kids child node list of the page collection, and assign a Count field based on the number of valid pages, thus completing the unified aggregation of PDF page resources.

[0062] S40. Top-level structure establishment. Create a new Catalog root object and bind the above page collection object to the Pages field of the directory root object; modify the Root node parameter of the PDF global cross-reference table to point to the newly created directory root object, and update the cross-reference table Size parameter according to the current largest object number to complete the missing index structure of the PDF top level and fix file structural faults.

[0063] S50, Fault Tolerance, File Output, and Resource Verification. This solution employs a tiered, fallback fault-tolerance logic, capturing runtime anomalies in real-time throughout the entire repair and structure creation process, distinguishing between different fault types such as object parsing anomalies, stream decompression anomalies, and structure creation anomalies. If the top-level structure creation fails or object parsing errors occur, the structure creation logic is terminated, and a PDF file is directly generated based on the repaired underlying PDF object data, achieving fallback repair. Finally, the structured PDF data is encapsulated into a binary data stream, outputting a complete PDF file that can be opened normally. Text data and bitmap image resources from each page of the repaired PDF are extracted in batches, and the number of pages, text content, and image resource integrity are verified to complete the repair result verification.

[0064] Another embodiment of the present invention provides a damaged PDF file repair device for performing the damaged PDF file repair method described above, such as... Figure 5 As shown, it includes: The data reading module U10 is used to read the binary data stream of the damaged PDF to be repaired and input the original data of the damaged PDF; The fragment splitting module U20 is used to scan the PDF binary data stream, identify the start and end markers of PDF objects, and split the data into several ordered PDF data fragments. The object repair module U30 is connected to the fragment splitting module and is used to parse PDF data fragments one by one, identify streaming data types, complete object stream decompression, nested sub-object splitting, compressed data decoding, and repair various basic PDF objects. The page creation module U40, connected to the object repair module, is used to filter PDF page objects, construct page collection objects, and summarize and associate all page resources. The structure creation module U50 is connected to the page creation module and is used to create a PDF directory object, bind a page set, configure the PDF root directory and cross-reference table parameters, and establish the PDF file structure. The file generation module U60 is connected to the structure establishment module and is used to encapsulate the established PDF file structure into a standard PDF binary file and output the repaired PDF file. The U70 fault tolerance module is used to capture program exceptions during the repair process and generate a repair file based on the original parsed data when the PDF file structure fails to be established.

[0065] The object repair module includes: The marker positioning unit is used to match the start and end markers of the stream within a PDF data segment to accurately locate the stream data interval; The object stream parsing unit is used to identify object stream identifiers and to split, traverse, and batch repair and write nested sub-objects. The compression decoding unit is used to identify the PDF Flate compression encoding identifier, decompress the compressed stream data using the DEFLATE lossless compression standard decoding algorithm, and update the PDF object resource data.

[0066] In one embodiment, the above-mentioned apparatus further includes a resource detection module, used to extract page text and page image resources of the repaired PDF file and verify the integrity of the PDF file resources.

[0067] This invention also provides an electronic device, including a memory, a processor, and a computer program stored in the memory and executable on the processor. When the processor executes the computer program, it implements the steps of the damaged PDF file repair method described in the above method embodiments.

[0068] This invention also provides a computer-readable storage medium storing a computer program. When executed by a processor, the computer program performs the steps of the damaged PDF file repair method described in the above-described method embodiments. The storage medium can be either volatile or non-volatile computer-readable storage.

[0069] This invention also provides a computer program product carrying program code. The program code includes instructions that can be used to execute the steps of the damaged PDF file repair method described in the above method embodiments. For details, please refer to the above method embodiments, which will not be repeated here.

[0070] The aforementioned computer program product can be implemented through hardware, software, or a combination thereof. In one optional embodiment, the computer program product is specifically embodied in a computer storage medium; in another optional embodiment, the computer program product is specifically embodied in a software product, such as a software development kit (SDK), etc.

[0071] Those skilled in the art will clearly understand that, for the sake of convenience and brevity, the specific working processes of the systems and devices described above can be referred to the corresponding processes in the foregoing method embodiments, and will not be repeated here. In the several embodiments provided by this invention, it should be understood that the disclosed systems, devices, and methods can be implemented in other ways. The device embodiments described above are merely illustrative. For example, the division of units is only a logical functional division; in actual implementation, there may be other division methods. Furthermore, multiple units or components may be combined or integrated into another system, or some features may be ignored or not executed. Another point is that the displayed or discussed mutual coupling or direct coupling or communication connection may be through some communication interfaces; the indirect coupling or communication connection of devices or units may be electrical, mechanical, or other forms.

[0072] The units described as separate components may or may not be physically separate. The components shown as units may or may not be physical units; that is, they may be located in one place or distributed across multiple network units. Some or all of the units can be selected to achieve the purpose of this embodiment according to actual needs.

[0073] In addition, the functional units in the various embodiments of the present invention can be integrated into one processing unit, or each unit can exist physically separately, or two or more units can be integrated into one unit.

[0074] If the aforementioned functions are implemented as software functional units and sold or used as independent products, they can be stored in a processor-executable, non-volatile, computer-readable storage medium. Based on this understanding, the technical solution of this invention, essentially, or the part that contributes to the prior art, or a portion of the technical solution, can be embodied in the form of a software product. This computer software product is stored in a storage medium and includes several instructions to cause a computer device (which may be a personal computer, server, or network device, etc.) to execute all or part of the steps of the methods described in the various embodiments of this invention. The aforementioned storage medium includes various media capable of storing program code, such as USB flash drives, portable hard drives, read-only memory (ROM), random access memory (RAM), magnetic disks, or optical disks.

[0075] Finally, it should be noted that the above-described embodiments are merely specific implementations of the present invention, used to illustrate the technical solutions of the present invention, and not to limit it. The scope of protection of the present invention is not limited thereto. Although the present invention has been described in detail with reference to the foregoing embodiments, those skilled in the art should understand that any person skilled in the art can still modify or easily conceive of changes to the technical solutions described in the foregoing embodiments within the technical scope disclosed in the present invention, or make equivalent substitutions for some of the technical features; and these modifications, changes, or substitutions do not cause the essence of the corresponding technical solutions to deviate from the spirit and scope of the technical solutions of the embodiments of the present invention, and should all be covered within the scope of protection of the present invention. Therefore, the scope of protection of the present invention should be determined by the scope of the claims.

Claims

1. A method for repairing damaged PDF files, characterized in that, Includes the following steps: Read the binary data stream of the damaged PDF to be repaired, scan and parse the binary data stream of the PDF, identify the start and end positions of all objects in the PDF file, and divide it into several independent PDF data segments; Each PDF data fragment is parsed and processed one by one to identify the stream data type within the PDF data fragment. Adaptive repair logic is executed for object streams, compressed decoding streams, and ordinary text objects respectively to restore the underlying object data of the damaged PDF. Iterate through all repaired PDF objects, filter all page objects, count the number of page objects and construct a page collection object, and associate all page objects; Create a PDF directory object, bind the page collection object to the PDF directory object, configure the PDF file root directory identifier and cross-reference table size parameters, and establish a complete PDF file structure; The completed PDF file structure is packaged into a standard PDF binary file to complete the repair of damaged PDF files; Extract the text content and image resources from the repaired PDF file, verify the integrity of the PDF page resources, and complete the file repair verification.

2. The method for repairing damaged PDF files according to claim 1, characterized in that, The PDF data fragment is obtained using the following steps: The PDF binary data stream is scanned using regular expression matching to match the start and end identifiers of PDF objects, marking the start and end offset positions of each PDF object. Based on the identifier matching results, the PDF data stream is sliced ​​to generate PDF data fragments carrying object numbers, start offsets, and end offsets, and all PDF data fragments are sorted according to object numbers.

3. The method for repairing damaged PDF files according to claim 1, characterized in that, The adaptation and repair logic is executed separately for object streams, compressed / decoded streams, and plain text objects, including: Extract the binary data of a single PDF data segment, match the start and end markers of the stream within the segment, and locate the stream data range of the PDF object; If the PDF data fragment contains an object stream identifier, the object stream is decompressed using the DEFLATE lossless compression and decompression algorithm, the object stream header parameters are parsed, multiple nested sub-objects within the object stream are split, and all sub-object data is repaired and written in batches. If the data fragment contains a PDF Flate compression encoding identifier, the compressed stream data is decompressed, the PDF object description text is retained, and the original stream data corresponding to the object is updated. If no valid stream data is available, the fragmented text data is read directly to complete the repair and writing of the ordinary PDF object.

4. The method for repairing damaged PDF files according to claim 1, characterized in that, The process involves traversing all repaired PDF objects, filtering all page objects, counting the number of page objects, constructing a page collection object, and associating all page objects, including: Iterate through all objects in the PDF file cross-reference table, identify PDF page objects of type "page", and summarize all valid page objects; create a new page collection object, associate all page objects with the child nodes of the page collection object, count the total number of pages, and write the count parameter of the page collection object.

5. The method for repairing damaged PDF files according to claim 1, characterized in that, The process of creating a PDF directory object involves binding the page collection object to the PDF directory object, configuring the PDF file root directory identifier and cross-reference table size parameters, and establishing a complete PDF file structure, including: Create a PDF directory object and bind the page collection object to the directory root object; modify the root node parameter of the PDF file cross-reference table to point the root node to the directory root object, and configure the cross-reference table size according to the maximum object number to repair the top-level structure of the PDF file.

6. The method for repairing damaged PDF files according to claim 1, characterized in that, Anomalies are captured in real time during the repair process. When an anomaly occurs in the PDF structure creation, a repair file is generated directly based on the original parsed PDF object data to avoid file repair failure.

7. A device for repairing damaged PDF files, characterized in that, A method for performing the damaged PDF file repair according to any one of claims 1-6 includes: The data reading module is used to read the binary data stream of the damaged PDF to be repaired, and input the original data of the damaged PDF; The fragment splitting module is used to scan the PDF binary data stream, identify the start and end markers of PDF objects, and split the data into several ordered PDF data fragments. The object repair module, connected to the fragment splitting module, is used to parse PDF data fragments one by one, identify streaming data types, complete object stream decompression, nested sub-object splitting, compressed data decoding, and repair various basic PDF objects. The page creation module, connected to the object repair module, is used to filter PDF page objects, construct page collection objects, and summarize and associate all page resources. The structure creation module, connected to the page creation module, is used to create PDF directory objects, bind page collections, configure PDF root directory and cross-reference table parameters, and establish the PDF file structure. The file generation module, connected to the structure establishment module, is used to encapsulate the established PDF file structure into a standard PDF binary file and output the repaired PDF file. An exception handling module is used to capture program exceptions during the repair process and generate a repair file based on the original parsed data when the PDF file structure fails to be built. The resource detection module is used to extract page text and page image resources from the repaired PDF file and verify the integrity of the PDF file resources.

8. The damaged PDF file repair device according to claim 7, characterized in that, The object repair module includes: The marker positioning unit is used to match the start and end markers of the stream within a PDF data segment to accurately locate the stream data interval; The object stream parsing unit is used to identify object stream identifiers and to split, traverse, and batch repair and write nested sub-objects. The compression decoding unit is used to identify the PDF Flate compression encoding identifier, decompress the compressed stream data using the DEFLATE lossless compression standard decoding algorithm, and update the PDF object resource data.

9. A computer-readable storage medium having a computer program stored thereon, characterized in that, When the computer program is executed by the processor, it implements the method for repairing damaged PDF files as described in any one of claims 1-6.

10. An electronic device comprising a memory, a processor, and a computer program stored in the memory and executable on the processor, characterized in that, When the processor executes the computer program, it implements the damaged PDF file repair method according to any one of claims 1-6.