A Method for Intelligent Layout and Optimized Printing of OA Approval Documents Based on a Dynamic Template Engine
By using a dynamic template engine and intelligent optimization algorithms, the problems of fixed templates and rigid resource scheduling in traditional OA systems have been solved. This enables personalized template design and efficient printing output, adapting to the needs of multiple departments and scenarios, reducing costs, and improving the level of office automation.
Patent Information
- Application Number
- CN202511438466.4
- Authority / Receiving Office
- CN · China
- Patent Type
- Patents(China)
- Current Assignee / Owner
- Filing Date
- 2025-10-10
- Publication Date
- 2026-03-03
- Estimated Expiration
- 2045-10-10
AI Technical Summary
Traditional OA systems use fixed templates for approval workflow printing, which are inflexible, unsuitable for adaptability, and unable to support the differentiated needs of multiple departments and scenarios. Non-technical personnel cannot operate them independently, and printing task scheduling relies on manual priority settings, which can easily lead to resource conflicts. The output document format does not match business requirements, resulting in repeated modifications and increased costs.
It adopts an intelligent layout and optimized printing method for OA approval documents based on a dynamic template engine. Through technical means such as template definition and storage, data binding, template generation and output, template management and expansion, task acceptance and parsing, task scheduling and optimization, resource allocation and monitoring, and fault detection and recovery, it can achieve personalized template design, intelligent template optimization and high-precision printing output, and support compatibility with a variety of printer devices.
It enables flexible and efficient personalized template design, improves approval efficiency, adapts to rapidly changing business environments, significantly reduces paper document processing costs, reduces resource waste, improves office automation levels, and provides synergistic benefits across technical fields.
Smart Images

Figure CN120911404B_ABST
Abstract
Description
Technical Field
[0001] This invention belongs to the technical field of office automation (OA) systems, and particularly relates to a method for intelligent layout and optimized printing of OA approval documents based on a dynamic template engine. Background Technology
[0002] Traditional OA system approval workflow printing methods have the following limitations: Fixed templates: Most systems use preset templates, making it impossible to flexibly adjust the layout, fields, or logic according to business needs (e.g., the fixed template problem mentioned in invention patent CN20191000123A). Poor adaptability: It is difficult to support the differentiated needs of multiple departments and scenarios, such as dynamically embedding compliance clauses and risk assessments in airport approvals.
[0003] The existing technology has the following shortcomings: It lacks user-friendly template design tools, making it impossible for non-technical personnel to operate independently. Print job scheduling relies on manual priority settings, which can easily lead to resource conflicts. The output document format does not match business requirements, resulting in repeated modifications and increased costs.
[0004] Based on the above analysis, the existing technologies have the following problems and shortcomings: In enterprise environments that heavily rely on information technology and digital management, office automation (OA) systems play a crucial role as important tools for improving work efficiency and simplifying workflows. However, in practical applications, traditional OA approval workflow printing methods are often constrained by limitations and suffer from both high costs and low efficiency, especially in the paper document printing process, which lacks an effective mechanism to adapt to complex approval logic and dynamically changing needs. Summary of the Invention
[0005] To overcome the problems existing in related technologies, the embodiments disclosed in this invention provide a method for intelligent layout and optimized printing of OA approval documents based on a dynamic template engine. In particular, it relates to a document layout method that is customized according to predefined strategies and rules, and combines dynamic data binding, intelligent optimization and resource scheduling technologies to realize personalized generation and efficient output of approval process documents.
[0006] The technical solution is as follows: A method for intelligent layout and optimized printing of OA approval documents based on a dynamic template engine, the method comprising:
[0007] S1, Template Definition and Storage: Users define various types of templates, including document templates and email templates. After the template is defined, the placeholders contained in the template are dynamically replaced with actual data when generating specific content. The defined templates are stored in an easily accessible and manageable location, including a database or file system.
[0008] S2, Data Binding and Replacement, uses a data binding mechanism to associate placeholders in the template with the data source; when the template is generated, the placeholders are automatically replaced with the corresponding actual data;
[0009] S3, Template Generation and Output: Users trigger the template generation process and specify the required data source to generate the final document or email. Users can then download, send, or save the document or email.
[0010] S4, Template Management and Extension: View, edit, delete, and create new templates through the template management interface; dynamically extend the templates by adding new template types or placeholders as needed through the template extension mechanism;
[0011] S5, Task Acceptance and Parsing: Receives print tasks, including document content, print settings, and print requirements. Parses the received tasks by extracting key information, including the number of document pages and the number of copies to be printed.
[0012] S6, Task Scheduling and Optimization: Based on the priority, urgency, and availability of printing resources, task scheduling is performed to optimize the printing order.
[0013] S7, Resource Allocation and Monitoring, allocates printing resources to each task to enable the task to proceed, monitors resource usage, including paper consumption, ink remaining, etc., and replenishes and adjusts resources in a timely manner.
[0014] S8, optimized print path and output;
[0015] S9, Fault Detection and Recovery.
[0016] Combining all the above technical solutions, the beneficial effects of this invention are as follows:
[0017] First, this invention aims to provide a more flexible, efficient, and personalized platform to adapt to the diverse needs of enterprises, including: Personalized template design: By introducing a graphical interface design tool, users can customize the layout of process nodes, information input methods, etc., to meet the requirements of specific business processes. This design allows non-technical personnel to quickly build complex approval process templates. Intelligent template optimization: Utilizing AI algorithms and machine learning technology to analyze historical approval data, automatically optimize template design, improve approval efficiency, and predict potential problems, thereby dynamically adjusting the template structure and process logic. High-precision printing output: Integrating an advanced document generation engine and printing service interface, ensuring accurate content and aesthetically pleasing layout during the conversion from electronic approval workflows to paper documents. It also supports compatibility with various printer devices to adapt to different environmental needs.
[0018] Secondly, this invention addresses the limitations of traditional OA systems through technological innovation and functional optimization, providing a flexible, efficient, and personalized solution. This method not only improves the efficiency and quality of approval processes but also offers organizations greater customization options, adapting to rapidly changing business environments.
[0019] Third, this invention achieves cross-technical collaboration and integration. By organically combining dynamic template engine technology, intelligent optimization algorithms, and modern printing control technology, it produces a synergistic gain effect that transcends the simple superposition of single technical fields. The technical solution of this invention provides significant and quantifiable technological progress. Experimental verification shows that it has achieved breakthrough improvements in key performance indicators (such as template processing efficiency, resource utilization, and task completion time) compared to existing technologies. It significantly reduces paper document processing costs, reduces resource waste, and improves the level of office automation, providing effective technical support for promoting green office and organizational digital transformation. Attached Figure Description
[0020] The accompanying drawings, which are incorporated in and form part of this specification, illustrate embodiments consistent with this disclosure and, together with the description, serve to explain the principles of this disclosure;
[0021] Figure 1 This is a flowchart of the intelligent layout and optimized printing method for OA approval documents based on a dynamic template engine provided in this embodiment of the invention;
[0022] Figure 2 This is a schematic diagram of the automatic placeholder replacement process provided in an embodiment of the present invention;
[0023] Figure 3 This is a schematic diagram of template generation and output provided in an embodiment of the present invention;
[0024] Figure 4 This is a schematic diagram of the template management interface provided in an embodiment of the present invention;
[0025] Figure 5 This is a task parsing flowchart provided in an embodiment of the present invention;
[0026] Figure 6 This is a schematic diagram of the three-layer scheduling model provided in an embodiment of the present invention;
[0027] Figure 7 This is a schematic diagram of printer status modeling provided in an embodiment of the present invention;
[0028] Figure 8 This is a resource allocation diagram provided in an embodiment of the present invention;
[0029] Figure 9 This is a fault self-healing flowchart provided in an embodiment of the present invention;
[0030] Figure 10 This is a schematic diagram illustrating the principle of the intelligent layout and optimized printing method for OA approval documents based on a dynamic template engine, as provided in an embodiment of the present invention. Detailed Implementation
[0031] To make the above-mentioned objects, features, and advantages of the present invention more apparent and understandable, specific embodiments of the present invention will be described in detail below with reference to the accompanying drawings. Many specific details are set forth in the following description to provide a thorough understanding of the present invention. However, the present invention can be practiced in many other ways different from those described herein, and those skilled in the art can make similar modifications without departing from the spirit of the present invention. Therefore, the present invention is not limited to the specific embodiments disclosed below.
[0032] This invention introduces a template engine that supports dynamic binding and secure replacement of multi-source data, enabling automatic generation and multi-format output of approval document content. Combined with an intelligent scheduling algorithm based on reinforcement learning and multi-constraint graph matching, it achieves multi-objective optimized allocation of printing tasks and resources. Furthermore, relying on real-time resource monitoring and digital twin technology, it constructs a print management system with self-healing and dynamic adjustment capabilities. This method significantly improves the automation level, printing efficiency, and resource utilization of OA approval document processing, solving the technical problems of poor template flexibility, rigid printing processes, and lack of intelligent resource scheduling in traditional systems.
[0033] Example 1, such as Figure 1 and Figure 10 As shown in the embodiment of the present invention, the intelligent layout and optimized printing method for OA approval documents based on a dynamic template engine includes:
[0034] S1, Template Definition and Storage: Users define various types of templates, including document templates, email templates, etc. After the template is defined, the placeholders contained in the template are dynamically replaced with actual data when generating specific content. The defined templates are stored in an easily accessible and manageable location, such as a database or file system.
[0035] For example, after the template definition is completed, the system dynamically replaces placeholders with actual data through the following steps:
[0036] S1.1, Placeholder Parsing: The system scans template files (such as XML / HTML) and matches placeholder formats using regular expressions. The specific steps for matching placeholder formats using regular expressions are as follows: (1) Pattern Compilation; (2) Text Scanning: Using the compiled Pattern object, a Matcher object is created for the template content to be parsed. This matcher will be responsible for searching for subsequences that match the pattern in the text. (3) Iterative Matching and Extraction: The matcher.find() method is called to iteratively search for the next matching subsequence in the template content. Whenever a match is found: the specific format of the match is checked. The match is determined to be in the format ${variable_name} by checking whether the capture group matcher.group(1) is not null. If it is, the value of the capture group is extracted as the key. If matcher.group(1) is null, it means that the match is in the format #{table_name.field_name}, and the value of the capture group matcher.group(2) is extracted as the key. Finally, the variable variableKey is assigned the extracted placeholder identifier (such as approver_name or expense_form.amount) for subsequent data binding and replacement operations. (4) Processing complete: When the matcher.find() method can no longer find more matches, the loop ends and the placeholder parsing stage is completed. The system has successfully identified all placeholders in the template that conform to the preset format and their specific content.
[0037] S1.2, Data Source Binding; includes: structured data sources, related database table fields (e.g., expense_form.amount), and data retrieval via an ORM framework (e.g., MyBatis). Dynamic Variables: Retrieving runtime variables (e.g., approver_name) from the approval context (e.g., BpmContextUtil). The process of retrieving runtime variables from the approval context (e.g., BpmContextUtil) can be described as follows: This process aims to dynamically retrieve variable values from the memory environment (i.e., the approval context) during process execution for use in placeholder replacements in the template (e.g., ${approver_name}).
[0038] S1.3, Type-safe replacement, including: formatting numeric placeholders (such as amounts, dates) (e.g., DecimalFormat("#,##0.00")). HTML escaping (to prevent XSS attacks) or truncation (to prevent overflow) of text placeholders. (1) Numeric Formatting: Purpose: to ensure that amounts, quantities, percentages, and other numerical values are displayed in a form that conforms to regional customs, is easy to read, and meets professional standards.
[0039] S1.4, Dynamic Rendering; includes: recursively processing nested placeholders using template engines (such as Freemarker, Thymeleaf).
[0040] S1.5, Result Validation: Validate unreplaced placeholders (e.g., Logger.warn("Unreplaced placeholder: " +variableKey)"). Perform syntax checks (e.g., XML closing tag validation) before generating the final document.
[0041] The syntax check performed before generating the final document is a crucial step in the system's process of validating the structure and validity of the intermediate content after all data binding and dynamic rendering are completed. This process aims to ensure the output document is correctly formatted and structurally complete, avoiding the generation of invalid documents due to template logic errors or data issues. The specific process is as follows:
[0042] (1) Content extraction and caching: The system caches the complete content (usually in string form) obtained after dynamic rendering into a temporary buffer as the input source for syntax checking.
[0043] (2) Document type identification and parser selection: The system automatically identifies the document type based on the preset output format (such as XML, HTML) or by analyzing the beginning of the content, and selects the corresponding syntax parser (such as XML parser, HTML parser) accordingly.
[0044] (3) Structured Syntax Check: The selected parser is invoked to rigorously parse and validate the cached content. Core checks include: Tag Closure Check: Ensures that all start tags have corresponding end tags and that the nesting order is correct. For example, checking each tag in the XML... <tag> There are corresponding ones< / tag> And without cross-nesting (e.g.) Attribute validity check: Checks whether the attributes of the tag conform to the specifications (e.g., whether the attribute name is valid, and whether the value is correctly enclosed in quotation marks). Special character escaping verification: Confirms that all reserved characters (such as <, >, & in XML) have been correctly escaped (e.g., <, >, &) to prevent parsing ambiguity. Document structure integrity check: Verifies whether the document has the necessary root element and conforms to the structure defined by the type (e.g., DTD, Schema).
[0045] (4) Error handling and logging: If the parser passes the validation successfully without throwing any exceptions, it indicates that the document syntax is correct and the process continues. If the parser throws an exception (such as SAXParseException), the exception is caught, error details (such as error type, line number, column number and specific content fragments) are recorded, and output through the log (such as Logger.error). At the same time, the generation process may be aborted or an alarm may be triggered.
[0046] (5) Passing the check and outputting the document: Only after all syntax checks are passed will the system treat the cached intermediate content as the final valid document and perform subsequent output operations (such as downloading, sending, or saving). Otherwise, an error message will be returned or the system will fall back to the secure version according to the policy.
[0047] (2) Object-Relational Mapping (ORM): The specific association methods that use data binding mechanisms to associate placeholders in templates with data sources (such as database records, user input, etc.); including direct key-value binding by storing the correspondence between variable names and values using Map, ORM field binding by associating database entity fields with JPA / Hibernate annotations, dynamic context binding by obtaining variables from the runtime environment (such as approval context, Session), and API data binding by calling external APIs (URL and parameter mapping need to be configured); see Table 1 for details.
[0048] Table 1 Data Binding Table
[0049]
[0050] Among these innovations, the invention further proposes the following: By utilizing a data binding mechanism to associate placeholders in the template with data sources (such as database records, user input, etc.).
[0051] Lazy loading is used for large data fields (such as attachment content), and data is only requested when it is replaced;
[0052] Cascading bindings support access to nested objects (e.g., #{expense.creator.department}).
[0053] Type converter, automatically handles data type differences (e.g., database BigDecimal to template string);
[0054] For example, see the automatic placeholder replacement process. Figure 2 Specifically, it includes:
[0055] Step 1, Placeholder Location: Use regular expressions to identify placeholders;
[0056] Step 2, Data Source Resolution: Select the data source type based on the placeholder prefix;
[0057] (1) Prefix Recognition and Classification: The system predefines a set of placeholder syntax rules, where different prefixes correspond to different data source types. The mapping relationship is shown in Table 2:
[0058] Table 2 Mapping Relationship Table
[0059]
[0060] (2) Routing and Data Acquisition: Based on the identified prefix, the system executes the corresponding data acquisition strategy:
[0061] For ${variable}: Action: Determines that data needs to be retrieved from the runtime context. Operation: Extract the string between the prefix and suffix as the key (e.g., the key of ${approver_name} is "approver_name"), and then use context_vars.get(key) or a similar method to look up the corresponding value in the in-memory context variable map.
[0062] For #{entity.field}: Action: Determines that data needs to be retrieved from the database (via ORM). Operation: Extracts the string between the prefix and suffix and parses it according to its rules (e.g., separated by dots). First, the entity or table to be queried is determined based on the first part, "entity" (e.g., "expense"). Then, the specific attribute to be retrieved is determined based on the subsequent part, "field" (e.g., "amount") or "field.subfield" (e.g., "creator.department"). Finally, the query is constructed and executed using an ORM framework (e.g., "orm_query(entity)") to obtain the target value.
[0063] For other prefixes (such as the hypothetical @{api.endpoint}): Action: Determine that an external API service needs to be called. Operation: Extract the identifier, parse it into a specific URL and parameters according to the pre-configured API mapping rules, initiate a network request and parse the response to extract the required data.
[0064] (3) Exception handling: If the data does not exist in the data source selected by the prefix, the system will handle it according to the preset strategy, such as recording a warning, using the default value, or throwing an exception to interrupt the process.
[0065] Step 3, Secure Replacement: Output secure data source through defensive processing;
[0066] This defensive process mainly includes the following core operations:
[0067] (1) Input cleaning and standardization: First, the raw data (rawValue, which may be of type String, Number, Date, etc.) from different data sources are uniformly converted into string form (rawValue.toString()) to provide a unified input for subsequent processing.
[0068] (2) Secure escaping: This is a core step in preventing code injection attacks (such as XSS). The system will escape special characters in the string according to the output context. For HTML output context: use utility classes such as HtmlUtils.htmlEscape() to convert characters with special HTML meanings in the string (such as <, >, &, ", ') into their corresponding HTML entities (such as <, >, &, ", '). This ensures that even if there are malicious script tags in the user input or database (such as <script>alert('xss')< / script> (This will also be displayed as plain text and will not be executed.)
[0069] (3) Type-aware formatting: After escaping, the system will further determine the essential type of the data and apply corresponding formatting rules, aiming to improve the professionalism and readability of the output.
[0070] Numeric recognition and formatting: Use methods such as NumberUtils.isNumber() to determine whether the escaped string represents a valid number. If so, call the corresponding formatting function (such as formatDecimal) to add thousands separators, standardize decimal places, etc., according to locale settings or business rules (for example, format 5000.5 as 5,000.50).
[0071] Non-numeric processing: If the content is not a number, use the string after safe escaping.
[0072] (4) Final replacement: Replace the safe string (escapedValue or formatted numeric string) obtained after the above "defensive processing" with the original placeholder position in the template.
[0073] Step 4, Loop / Condition Processing: Process complex structures recursively;
[0074] The specific implementation steps are as follows:
[0075] (1) Initial call and data model input: When the user triggers template generation, the system passes a "data model" containing all the data to be replaced to the template engine. This data model may be a simple key-value pair map or a nested structure containing complex objects and lists.
[0076] (2) Template scanning and instruction recognition: The template engine begins scanning the template content. When it encounters a control instruction (such as Freemarker's <#list ...> or <#if ...>), it knows that what needs to be processed next is a complex structure, not a simple placeholder.
[0077] (3) Entering the recursive processing branch: For loop instructions (such as <#list expenses as item>): The engine first retrieves a variable named expenses from the dataModel. It expects this to be a collection (such as a List or Array). The engine begins to iterate through each element in this collection. For the current element (named item in the instruction), the engine creates a new, local context in which the item variable points to the element currently being processed. The engine recursively iterates through <#list> and< / #list> All template content between tags is processed. This means that within this local context, the engine will again execute the complete "scan-identify-replace" process. In this local process, if ${item.date} is encountered, the engine will look for the item object within the local context and extract the date attribute. If the item object itself contains deeper nested objects (e.g., ${item.department.name}), the engine will continue recursively deeper until it obtains the final name string value. After processing all content of the current item, the engine moves to the next element in the collection and repeats the above steps until all elements have been traversed. For conditional directives (such as <#if amount>1000>): the engine first evaluates the conditional expression (amount>1000). If the condition is true, the engine will recursively process <#if> and< / #if> The template content between these elements. Similarly, when processing this part, the engine will again execute the complete "scan-identify-replace" process, which can handle any placeholders or nested control instructions contained within.
[0078] (4) Basic data type processing: When the recursion goes deep to the bottom layer and the engine encounters a basic data type (such as item.date or item.amount), it will stop the recursion and perform the standard "placeholder replacement" process, including type-safe formatting (such as formatting the date as 'yyyy-MM-dd') and safe escaping.
[0079] (5) Result merging and return: The engine will merge all the fragments generated by recursive processing (such as the contents of each row in the list) in order to finally generate a complete document with data populated.
[0080] For example, during the automatic placeholder replacement process, for exception types, the placeholder is automatically replaced through an exception handling mechanism. The exception handling mechanism includes: for exception types where the placeholder is not bound, a warning is recorded and the original placeholder is retained (or replaced with an empty string); for exception types where the data type does not match, a type converter is called to force conversion; for exception types where the data source is unavailable, cached data or default values are enabled (configured as default:"N / A"). The effects brought by the present invention through the above technical features are shown in Table 3.
[0081] Table 3 Comparison of Results
[0082]
[0083] S3, Template Generation and Output: Users trigger the template generation process and specify the required data source to generate the final document or email. Users can then download, send, or save the document or email. Template generation and output are as follows: Figure 3 As shown. Specifically includes:
[0084] Step S3.1: The user triggers a REST API request and passes parameters;
[0085] Users select the template type (document / email), data source (such as approval form ID process_instance_id=123), and output format (PDF / DOCX / plain text, etc.) through the front-end interface.
[0086] Step S3.2 Template engine processing: Dynamically select the template engine based on the file type. For document templates, select the Apache Freemarker engine; for email templates, select the Thymeleaf engine; see Table 4.
[0087] Table 4. Thymeleaf Engine Table
[0088]
[0089] Exemplary implementation (Freemarker generating HTML):
[0090] Step S3.3 Format conversion and rendering, including document generation and email generation; document generation includes: using open source libraries to convert HTML to PDF / DOCX; email generation includes: building MIME emails (supporting HTML body and attachments).
[0091] Step S3.4 Output control includes multi-channel output for downloading files, sending emails, and saving to cloud storage; see Table 5 for multi-channel output.
[0092] Table 5 Multi-channel output table
[0093]
[0094] For example, the key technological innovations in step S3.3, format conversion and rendering, include:
[0095] During document generation, dynamic format adaptation allows the same template to generate different output formats (such as HTML → PDF or DOCX), and the renderer is automatically selected via OutputFormatResolver. Detailed steps are as follows:
[0096] (1) Receiving user output format requests: When a user triggers a document generation request through the front-end interface or API, they will explicitly specify the desired output format. For example, in a REST API request, the parameter outputFormat: "pdf" or outputFormat: "docx" will be passed to the back-end service. This step is the starting point of the entire dynamic adaptation process.
[0097] (2) Calling the Format Resolver: After receiving the outputFormat parameter, the system calls a factory method called resolveRenderer. This method is the core of the "dynamic format adaptation" function of this invention. Processing logic: The method uses a switch statement to match the passed format string. If the format is "pdf", an instance of the PdfRenderer class is created and returned. If the format is "docx", an instance of the DocxRenderer class is created and returned. If the format is not supported (such as "txt"), an UnsupportedFormatException is thrown to notify the user or the upstream system. Output: Returns a concrete renderer object that implements the DocumentRenderer interface. This interface defines common methods such as render(htmlContent, outputStream) to ensure consistency of behavior between different renderers.
[0098] (3) Format Conversion: After obtaining the specific renderer object (such as PdfRenderer), the system calls its render method, taking the HTML intermediate document containing all dynamic data previously generated by the template engine as input, and performs format conversion. PdfRenderer's function: It uses libraries such as Apache PDFBox or iText to parse the structure and styles of the HTML, accurately converting it to PDF format. It handles pagination, font embedding, image rendering, etc., ensuring that the layout of the PDF document is consistent with the HTML preview. DocxRenderer's function: It uses libraries such as Apache POI or docx4j to map the HTML content to paragraphs, tables, styles, and other elements in the Word document, generating an editable .docx file.
[0099] (4) Output the final document: The renderer writes the converted binary data stream (PDF or DOCX) to the specified output stream. This output stream can be connected to: an HTTP response for download by the user's browser; a file system for local storage; a cloud storage service (such as Alibaba Cloud OSS) for archiving; or an email service for sending as an attachment. For example, in email generation, email-document linkage is included: when the document is attached to an email, it is automatically compressed and encrypted (ZIP+AES256) to protect sensitive data.
[0100] For example, in step S3.4 output control, version control is performed, and each time a record template version + data snapshot is generated, traceability is supported (database table design example), see Table 6;
[0101] Table 6 Database Design Table
[0102]
[0103] Step 1: Calculate the template version fingerprint (template_version); Purpose: To uniquely identify the template used to generate the document, ensuring that the template has not been tampered with. Process: The system obtains the complete source code of the template currently used for rendering (e.g., a Freemarker or Thymeleaf template string stored in the database). An MD5 hash is performed on the template source code. MD5 is a widely used cryptographic hash function that can map data of arbitrary length to a 32-bit hexadecimal string. The calculated MD5 value (e.g., a3f5e2c8b1d7...) is used as the value of the template_version field.
[0104] The innovation lies in using hash values instead of simple version numbers (such as v1.0) to identify templates, allowing for precise detection of even the slightest changes. Even modifying a single punctuation mark will result in a completely different MD5 value, thus eliminating the risk of "same version number but different content."
[0105] Step 2: Capture and serialize a data snapshot (data_snapshot); Purpose: To completely record all dynamic data relied upon when generating the document, ensuring that the document can be reproduced with the same data at any time. Process: Before the template engine performs data binding and replacement, the system performs a deep copy of the entire data model currently used for rendering. This data model is a complex object containing the values corresponding to all placeholders, which may include database query results, runtime variables, API return data, etc. This deep-copied data object is converted into a structured JSON string using JSON serialization technology. This JSON string is then stored in the database as the value of the data_snapshot field. For example: Innovation: Traditional logs may only record key fields, while this invention records a complete, structured data snapshot. This allows for tracing back to not only who approved it, but also the specific content of each item in the list at that time, achieving a "time freeze" at the data level.
[0106] Step 3: Calculate the output file checksum (output_hash); Purpose: To create a unique "digital fingerprint" for the final generated file (such as PDF, DOCX) to verify the file's integrity and authenticity, preventing tampering during storage or transmission. Process: Before the file is generated and ready for output (download, send, or save), the system reads the entire binary content of the file. A SHA-256 hash operation is performed on this binary content. SHA-256 is a more secure cryptographic hash function than MD5, producing a 64-bit hexadecimal string. The calculated SHA-256 value (e.g., f4b3a1c2d5e6...) is used as the value of the output_hash field. Innovation: SHA-256 is used instead of MD5 because it has stronger collision resistance and is more suitable for scenarios requiring high security. By verifying the output_hash, it can be ensured that the file downloaded by the user is completely consistent with the original file generated by the system.
[0107] Step 4: Persistent Storage; Purpose: To store the above three key pieces of information along with the metadata of the generated task (such as generation time, operator, task ID, etc.) into the database. Process: The system constructs a new database record containing the following core fields: id: Automatically generated unique primary key. template_version: The template MD5 value calculated in Step 1. data_snapshot: A snapshot of the JSON data generated in Step 2. output_hash: The file SHA-256 value calculated in Step 3. generated_at: Current timestamp. generated_by: The ID or username of the current operator. task_id: The associated print or generation task ID. This record is then inserted into a dedicated "document version control table" (such as document_version_audit).
[0108] S4, Template Management and Extension: View, edit, delete, and create new templates through the template management interface; dynamically extend the templates by adding new template types or placeholders as needed through the template extension mechanism.
[0109] For example, the template management interface is as follows: Figure 4 As shown; viewing, editing, deleting, and creating new templates through the template management interface includes:
[0110] The first step is template lifecycle management; see Table 7.
[0111] Table 7 Template Lifecycle Management Table
[0112]
[0113] The second step is template syntax validation (real-time). For example, new template types or placeholders are dynamically added as needed through the template extension mechanism, including the extension type and implementation. Specifically, for new template types, the template renderer is dynamically loaded through a plug-in architecture (SPI mechanism) for dynamic extension. For custom placeholders, the extension interface is defined by registering a placeholder resolver for dynamic extension. In addition, for style extensions, style rules are dynamically injected using a CSS-in-JS solution for dynamic extension. See Table 8.
[0114] Table 8 Dynamic Expansion Table
[0115]
[0116] S5, Task Acceptance and Parsing, receives print jobs, including document content, print settings (such as paper size, print quality, etc.) and print requirements (such as duplex printing, binding, etc.). It parses the received task by extracting key information, such as the number of document pages and the number of copies to be printed. The task parsing process employs a multi-stage process, such as… Figure 5 As shown. For example, the improvements to the core multi-stage parsing algorithm are shown in Table 9;
[0117] Table 9. Improvements to the Core Algorithm
[0118]
[0119] S6, Task Scheduling and Optimization: Based on the priority, urgency, and availability of printing resources (such as printers, paper, ink, etc.), task scheduling is performed to optimize the printing order and reduce waiting time and resource waste. For example, a three-layer scheduling model is used for task scheduling. Figures 6-9 As shown in the figure; Table 10 shows the comparison between the three-layer scheduling model and existing technologies;
[0120] Table 10 Comparison of the Three-Level Scheduling Model with Existing Technologies
[0121]
[0122] For example, task scheduling specifically includes: Step I. Dynamic priority calculation; calculating the comprehensive priority using fuzzy logic + entropy weight method. Specific implementation steps:
[0123] (1) Indicator Selection and Data Collection: Purpose: To determine the key dimensions affecting task priority. Process: The system extracts three core indicators from the "Key Information Matrix" (from S5.4): task.deadline: Represents the urgency of the task. The closer the deadline, the higher the urgency. task.user_rank: Represents the importance of the task. For example, a task submitted by the CEO is more important than a task submitted by an ordinary employee. task.paper_usage: Represents the resource cost of the task. The more resources consumed, the higher the cost, and the lower the priority should be.
[0124] (2) Data Normalization: Purpose: To transform raw data with different dimensions and value ranges to a unified scale (usually the range [0, 1]) for fair comparison and weighted calculation. Process: Forward normalization is performed on deadline and user_rank (the larger the value, the higher the priority). For example, urgency = normalize(task.deadline) might be (max_deadline - task.deadline) / (max_deadline - min_deadline). Inverse normalization is performed on paper_usage because resource consumption is a cost, and the higher the cost, the lower the priority should be. resource_cost = 1 - normalize(task.paper_usage). Here, normalize(task.paper_usage) maps paper consumption to [0,1], with a larger value for more consumption; 1 - ... reverses this, with a smaller resource_cost for more consumption.
[0125] (3) Entropy Weighting: Objective: To solve the problem of "how to assign weights to the three indicators of urgency, importance, and resource cost". Entropy weighting is an objective weighting method that determines the weights based on the dispersion (information entropy) of the data of each indicator. The greater the data fluctuation (the smaller the entropy), the more information the indicator provides, and the greater its weight in the comprehensive evaluation. Process: The system collects the normalized indicator values of all tasks to be scheduled, forming an indicator matrix. Calculate the entropy value of each indicator. The smaller the entropy value, the greater the difference between different tasks, and the higher its contribution to task ranking. Calculate the weight of each indicator based on the entropy value. The formula is roughly: weight = (1 - entropy value) / Σ(1 - entropy value of each indicator). Output: A weight vector weights = [w1, w2, w3] is obtained, for example [0.5, 0.3, 0.2], which means that urgency accounts for 50%, importance accounts for 30%, and resource cost accounts for 20%.
[0126] (4) Fuzzy Inference: Purpose: To input normalized index values and objective weights into a "fuzzy inference system," simulating the decision-making process of human experts, handling fuzzy concepts such as "high," "medium," and "low," and outputting the final priority. Process: Define fuzzy sets: Define fuzzy linguistic variables for each input index and output priority. Input: urgency can be {low, medium, high}; importance can be {low, medium, high}; resource_cost can be {low, medium, high}. Output: priority can be {defer, normal, high, critical}. Establish a fuzzy rule base: This is a manifestation of human expert knowledge. For example: IF urgency IS high THEN priority IS critical (If it is urgent, then the priority is "critical") IF importance IS low AND resource_cost IS high THEN priority IS defer (If it is not important and resource-intensive, then the priority is "deferred"), IF urgency IS medium AND importance IS high THEN priority IS high. Fuzzy reasoning and defuzzification: (1) Map the normalized input value (e.g., urgency=0.8) to the corresponding fuzzy set (e.g., the membership degree of "high" is 0.9, and the membership degree of "medium" is 0.1). (2) Calculate the activation intensity of each rule according to the fuzzy rule base. (3) Aggregate the outputs of all activated rules. (4) Use defuzzification methods such as "center of gravity method" to convert the fuzzy output set into a precise priority score (e.g., 0.92). Weighted fusion: In the reasoning process, the weights calculated by the entropy weight method will be combined to adjust the influence of different indicators. (5) Output Final Priority: Purpose: To generate a floating-point number between 0.0 and 1.0 as the final comprehensive priority of the task. Process: The fuzzy inference system outputs a precise value, such as 0.92. This value will be passed to "Step II. Resource-Aware Scheduling Algorithm" as an important input parameter for its task-resource matching optimization. Step II. Resource-Aware Scheduling Algorithm; Specific Implementation Steps (Based on Improved Genetic Algorithm GA):
[0127] (1) Problem Modeling and Chromosome Encoding: Objective: To transform the scheduling problem into a "chromosome" form that can be handled by genetic algorithms. Process: Define "genes": Each "gene" represents a task-printer assignment pair. For example, Gene(taskId=5, printerId=2, startTime=100) means assigning task 5 to printer 2 and starting printing at time 100. Define "chromosomes": A "chromosome" represents a complete scheduling scheme, that is, the set of assignments for all tasks to be scheduled. For example, Chromosome = [Gene1, Gene2, ..., GeneN]. Encoding method: Integer encoding is used, and printerId and startTime are both represented by integers.
[0128] (2) Initialize the population: Objective: To generate a set of random and diverse initial scheduling schemes. Process: Randomly generate N chromosomes (e.g., N=100), each chromosome containing random assignment schemes for all tasks, forming the initial population.
[0129] (3) Define the Fitness Function: Purpose: To evaluate the "goodness" of a scheduling scheme. This is the core guiding principle of algorithm optimization. Process: The fitness function is a multi-objective function that aims to maximize the weighted sum of the following indicators: High-priority task completion rate: High-priority tasks should be assigned and completed first. Resource utilization rate: Resources such as printers, paper, and ink should be used efficiently to avoid idleness. User satisfaction: The actual completion time of a task should be as close as possible to or better than its expected time. Load balancing: Avoid overloading one printer while other printers are idle. Formula example: Fitness = α * (Σ(task priority * task completion status)) + β * (resource utilization rate) + γ * (1 / average waiting time) + δ * (load balancing rate) Where, α, β, γ, and δ are weight coefficients adjusted according to business needs.
[0130] (4) Selection: Purpose: To select individuals with high fitness (good scheduling scheme) from the current population as "parents" for breeding the next generation. Process: Using methods such as "roulette wheel selection" or "tournament selection", individuals with higher fitness have a greater probability of being selected.
[0131] (5) Crossover: Purpose: To combine the superior genes of two parent individuals through "hybridization" to produce new, potentially superior offspring individuals. Process: Randomly select two parent chromosomes, randomly select a crossover point, exchange the gene segments after the crossover point, and generate two new offspring chromosomes.
[0132] (6) Mutation: Purpose: To introduce random changes, increase population diversity, and avoid the algorithm getting stuck in local optima. Process: Basic mutation: Randomly change the printerId or startTime of a gene with a certain probability. Improvement - Introduction of simulated annealing: To more effectively escape local optima, this invention introduces the idea of simulated annealing. The probability or intensity of mutation will be dynamically adjusted ("cooling down") as the number of algorithm iterations increases. In the early stage, a larger range of mutations is allowed (high temperature, exploring the global optimum); in the later stage, the range of mutations gradually shrinks (low temperature, fine-tuning the search for local optima). Code illustration: ifrandom() <exp(-1 / temp): swap_random_genes(chromosome)
[0133] (7) Elite Retention and Iteration: Objective: To ensure that the best individuals in each generation are not lost and to gradually approach the global optimum. Process: The individuals with the highest fitness in each generation are directly retained to the next generation. Then, new individuals generated by selection, crossover, and mutation are used to fill the remaining positions, forming a new generation of population. This process is repeated until the preset number of iterations or fitness convergence is reached.
[0134] (8) Output the optimal scheduling scheme: Purpose: Decode the finally found optimal chromosome into specific task allocation instructions. Process: After the algorithm ends, select the chromosome with the highest fitness, parse out the Gene array contained in it, and obtain the final scheduling scheme of which printer each task should be assigned to and when printing should start. This scheme will be passed to the "Step S7 Resource Allocation and Monitoring" module for execution. Improved Genetic Algorithm (GA) Implementation Steps: Chromosome Encoding: Each gene represents a task-printer allocation scheme; Performance optimization effect is shown in Table 11;
[0135] Table 11 Performance Optimization Effects
[0136]
[0137] S7, Resource Allocation and Monitoring, allocates printing resources to each task to enable the task to proceed, monitors resource usage such as paper consumption and ink remaining, and replenishes and adjusts resources in a timely manner.
[0138] For example, resource allocation adopts a dynamic allocation architecture, such as... Figure 8 As shown; specifically including: resource allocation using a multi-constraint graph matching algorithm;
[0139] Step 1: Constructing the Weighted Bipartite Graph. Purpose: To abstract the "task" and "printer" in the physical world and their interrelationships into a mathematical graph model.
[0140] Step 2: Defining the Matching Objective. Objective: To clarify the problem the algorithm aims to solve. Process: Find a matching M. Matching M is a subset of the edge set that must satisfy a hard constraint: in matching M, any vertex (whether a task or a printer) can appear in at most one edge. This guarantees a "one-to-one" assignment: a task will not be assigned to multiple printers, and a printer will not process multiple tasks simultaneously. Among all possible matchings that satisfy the "one-to-one" constraint, find the matching with the largest total weight. That is: Maximize: Σ_{(i,j) ∈ M} Score_{ij} In simpler terms: Maximize the sum of the "satisfaction" of all pairings while ensuring fairness (one task per person).
[0141] Step 3: Applying the Matching Algorithm Purpose: To solve the "maximum weight matching" problem defined above using an efficient mathematical algorithm. Process: (1) Algorithm selection: The system calls the max_weight_matching function in the graph computing library (such as Python's NetworkX). This function usually implements the Kuhn-Munkres algorithm (Hungarian algorithm) or its optimized version for sparse or large-scale graphs. (2) Algorithm execution: The algorithm receives the weighted bipartite graph G constructed in the previous step as input. The algorithm iteratively calculates through a series of complex mathematical operations (such as vertex adjustment and finding augmenting paths). Finally, the algorithm outputs an optimal matching result M. This result is a dictionary or set containing all selected edges. For example: {('task_0', 'printer_2'), ('task_1','printer_0'), ('task_2', 'printer_1')}.
[0142] Step 4: Executing the Allocation. Purpose: To transform the mathematical results calculated by the algorithm into actual system operations.
[0143] Process: (1) The system parses the results of optimal_matching. (2) For each edge (task_i, printer_j) in the matching results: the system formally assigns task_i to printer_j. The system updates the resource status of printer_j (e.g., subtracts the demand of task_i from its A4 paper inventory). The system updates the status of task_i to "assigned" and records the printer ID to which it was assigned. (3) Unmatched tasks (if they exist, usually because printer resources are temporarily insufficient) will be placed in a waiting queue to wait for the next round of assignment.
[0144] For example, monitoring resource usage includes: a) multimodal sensor data acquisition, see Table 12;
[0145] Table 12 Multimodal Sensing Data Acquisition Table
[0146]
[0147] b) Time series anomaly detection; using LSTM-Autoencoder to detect abnormal consumption: Step 1: Data acquisition and preprocessing Purpose: To prepare high-quality time series data for model training and inference. Process: (1) Multimodal data acquisition: The system collects consumption data of various resources in real time through sensors deployed on the printer (such as photoelectric sensors, ink counting chips) or from the printer driver / API. According to the code input_shape=(60, 4), the system will collect 4 key parameters, such as: param_1: Number of A4 sheets consumed per minute. param_2: Acid ink consumption per minute (ml). param_3: Magenta ink consumption per minute (ml). param_4: Number of pages printed per minute (as context reference).
[0148] (2) Constructing time windows: The system slices the continuously collected data into fixed time windows. The 60 in the code indicates that each window contains 60 consecutive minutes of historical data. For example, the system will generate a data matrix of shape (60, 4), where 60 rows represent 60 time steps (minutes) and 4 columns represent 4 parameters.
[0149] (3) Data normalization: Since different parameters have different units and numerical ranges (e.g., the number of sheets of paper is an integer, and the amount of ink is a decimal), the system will normalize the data (e.g., Min-Max Scaling or Z-Score standardization) to scale all values to the range of [0, 1] or [-1, 1] to accelerate model convergence and improve accuracy.
[0150] Step 2: Build and train the LSTM-Autoencoder model; Objective: To train a neural network that can "remember" normal consumption patterns.
[0151] Step 3: Real-time monitoring and anomaly detection; Objective: To detect anomalies in real time using a trained model in a production environment.
[0152] Step 4: Model Update and Iteration; Purpose: To ensure the model can adapt to normal pattern drift caused by equipment aging, business changes, etc. Process:
[0153] (1) The system will periodically (e.g., weekly) or after confirming that a certain “abnormal” is actually a new “normal” pattern, add this new data to the training set.
[0154] (2) Use the updated training set to fine-tune or retrain the model so that it can continue to learn and adapt to the latest normal state.
[0155] S8 optimizes the print path and output based on the characteristics and requirements of the printing device to reduce printing time and improve print quality. It also formats the output, such as adjusting font size, color, and alignment, to meet printing requirements.
[0156] S9, fault detection and recovery, monitors the device status in real time during printing, such as paper clogging and insufficient ink. Once a fault is detected, recovery measures are taken immediately, such as clearing paper clogging and replacing ink, to ensure that the printing task can be completed smoothly.
[0157] The above description is only a preferred embodiment of the present invention, but the scope of protection of the present invention is not limited thereto. Any modifications, equivalent substitutions and improvements made by those skilled in the art within the scope of the technology disclosed in the present invention and within the spirit and principles of the present invention should be covered within the scope of protection of the present invention.
Claims
1. A method for intelligent formatting and optimized printing of OA approval documents based on a dynamic template engine, characterized in that... This method achieves intelligent formatting and efficient printing of approval documents through a dynamic template engine, specifically including the following steps: S1, Template Definition and Storage: Define various types of templates, including document templates and email templates; after the template definition is completed, the placeholders contained in the template are dynamically replaced with actual data when generating specific content; store the defined templates in an easily accessible and manageable location, including a database or file system; S2, Data Binding and Replacement, uses a data binding mechanism to associate placeholders in the template with the data source; when generating the template, the placeholders are automatically replaced with the corresponding actual data; S3, Template Generation and Output: By triggering the template generation process and specifying the required data source, the final document or email is generated, and the document or email can be downloaded, sent, or saved. S4, Template Management and Extension: View, edit, delete, and create new templates through the template management interface; dynamically extend the templates by adding new template types or placeholders as needed through the template extension mechanism; S5, Task Acceptance and Parsing: Receives print tasks, including document content, print settings, and print requirements. Parses the received tasks by extracting key information, including the number of document pages and the number of copies to be printed. S6, Task Scheduling and Optimization: Based on the priority, urgency, and availability of printing resources, task scheduling is performed to optimize the printing order. S7, Resource Allocation and Monitoring, allocates printing resources to each task to enable the task to proceed, monitors resource usage, including paper consumption and ink remaining, and replenishes and adjusts resources in a timely manner. S8, optimized print path and output; S9, fault detection and recovery; In step S2, the automatic replacement of placeholders includes: S2.1, Placeholder Location: Identify placeholders using regular expressions; S2.2, Data source parsing: Select the data source type based on the placeholder prefix; S2.3, Secure Replacement: Outputs a secure data source through defensive processing; S2.4, Loop / Conditional Processing: Processing complex structures recursively; During the automatic replacement of placeholders, an exception handling mechanism is used to automatically replace placeholders for exception types. The exception handling mechanism includes: for placeholders that are not bound to an exception type, a warning is recorded and the original placeholder is retained. For exceptions where the data type does not match, a type converter is used to force a conversion. For exceptions where the data source is unavailable, enable cached data or default values; In step S3, generating the final document or email includes: S3.1, triggers REST API requests and parameter passing; selects template type, data source, and output format through the front-end interface; S3.2 Template engine processing dynamically selects the template engine based on the file type. For document templates, the Apache Freemarker engine is selected, and for email templates, the Thymeleaf engine is selected. S3.3 Format Conversion and Rendering, including document generation and email generation; document generation includes: converting HTML to PDF / DOCX using open-source libraries; email generation includes: building MIME emails; in document generation, dynamic format adaptation allows the same template to generate different output formats, and OutputFormatResolver automatically selects the renderer; in email generation, email-document linkage is included: when a document is attached to an email, it is automatically compressed and encrypted using ZIP and AES256 to protect sensitive data; S3.4 Output control includes multi-channel output via file download, email sending, and cloud storage; version control is implemented in the output control, adding a data snapshot to each generated record template version, supporting traceability.
2. The intelligent layout and optimized printing method for OA approval documents based on a dynamic template engine according to claim 1, characterized in that, In step S1, after the template definition is completed, the dynamic replacement of placeholders with actual data is achieved through the following steps: S1.1, Placeholder parsing: The system scans the template file and matches the placeholder format using regular expressions; S1.2, Data source binding: Structured data source, associated with database table fields, and data is queried through the ORM framework; For dynamic variables, retrieve runtime variables from the approval context; S1.3, Type-safe replacement, formats numeric placeholders; performs HTML escaping or truncation on text placeholders; S1.4, dynamic rendering; uses a template engine to recursively process nested placeholders; S1.5, Result Validation: Validates unreplaced placeholders and performs a syntax check before generating the final document.
3. The intelligent layout and optimized printing method for OA approval documents based on a dynamic template engine according to claim 1, characterized in that, In step S2, the data binding mechanism achieves dynamic connection between the template and the data source through a data binding architecture with a three-layer association model. The three-layer association model includes: Template layer, defines the placeholder syntax rules; The mapping layer establishes the association between placeholders and data sources, including key-value pair mapping and ORM object relationship mapping. The data source layer provides structured data; The data binding mechanism associates placeholders in the template with the data source, including: direct key-value binding using a Map to store the mapping between variable names and values; ORM field binding by associating database entity fields with JPA / Hibernate annotations; dynamic context binding by retrieving variables from the runtime environment; and API data binding by calling external APIs. Furthermore, the data binding mechanism associates placeholders in the template with the data source, including: Lazy loading uses lazy loading for large data fields, requesting data only when it is replaced; Cascading binding supports access to nested objects; Type converter, automatically handles differences in data types.
4. The intelligent layout and optimized printing method for OA approval documents based on a dynamic template engine according to claim 1, characterized in that, In step S4, viewing, editing, deleting, and creating new templates through the template management interface includes: The first step is template lifecycle management; The second step is template syntax validation. New template types or placeholders are added dynamically as needed through a template extension mechanism. Specifically, for new template types, a plugin architecture is used to dynamically load the template renderer for dynamic extension; for custom placeholders, an extension interface is defined by registering a placeholder resolver for dynamic extension.
5. The intelligent typesetting and optimized printing method for OA approval documents based on a dynamic template engine according to claim 1, characterized in that, In step S5, the task parsing adopts a multi-stage parsing process; The received task is parsed by extracting key information, including: S5.
1. Structured data parsing is performed using adaptive template matching, and unstructured data parsing is performed using a visual-semantic joint model. Among them, structured data parsing using adaptive template matching includes: dynamically validating fields using extended JSON Schema and supporting default value filling. Unstructured data parsing is performed using a visual-semantic joint model. The unstructured data parsing includes: an OCR stage, using an improved TRBA model to extract text from print task sheets; and an NLP stage, based on domain knowledge graphs for entity recognition, including: constructing a print domain entity library and using a BiLSTM-CRF model for sequence labeling; the sequence labeling using the BiLSTM-CRF model includes both the original text and the labeled results. S5.2 Dynamic rule engine verification; S5.3 Real-time rule updates: Push new rules via WebSocket and obtain a key information matrix; S5.4 Optimize the obtained key information matrix for tasks, including: task scheduling based on reinforcement learning and resource conflict prediction; Reinforcement learning-based task scheduling includes: dynamically adjusting task priorities using the DQN algorithm; For the state space: printer queue length, current task page count, remaining ink level; Using the reward function: R = \alpha \times \frac{1}{waiting time} + \beta \times ink balance; The resource conflict prediction includes: establishing a directed graph model of printed resources and using topological sorting to detect infeasible task combinations.
6. The intelligent layout and optimized printing method for OA approval documents based on a dynamic template engine according to claim 1, characterized in that, In step S6, a three-layer scheduling model is adopted for task scheduling; Task scheduling specifically includes: S6.1 Dynamic Priority Calculation: The comprehensive priority is calculated using fuzzy logic and entropy weighting. S6.2 Resource-aware scheduling algorithm, including the improved genetic algorithm GA to implement resource-aware scheduling; S6.3 Real-time resource monitoring and prediction; including: printer status modeling, LSTM ink level prediction; Optimizing the printing order includes: time window optimization, conflict resolution mechanisms including resource conflict detection; resolution strategies including priority preemption, resource replacement, and task fragmentation; and load balancing strategies, such as printer allocation based on consistent hashing.
7. The intelligent layout and optimized printing method for OA approval documents based on a dynamic template engine according to claim 6, characterized in that, In step S7, resource allocation adopts a dynamic allocation architecture. The specific implementation steps of printer allocation based on consistent hashing include: (1) Construct a consistent hash ring: Organize the entire hash space into a ring structure with the beginning and end connected; each point on the ring corresponds to a hash value; (2) Mapping printer nodes: Based on the unique identifier of each printer, calculate its hash value using a hash function and map the printer to the corresponding position on the hash ring; (3) Mapping printing tasks: For each printing task to be scheduled, calculate the hash value based on a key attribute of the task and map it to a point on the hash ring. (4) Assign printers to tasks: Starting from the position of the printing task mapped on the ring, search clockwise and assign the task to the first printer node found; (5) Handling node addition and removal: When a printer fails and goes offline or a new printer comes online, simply remove the mapping of the node on the ring or add the mapping of the new node; only the tasks from the new node to the next node in the counterclockwise direction are affected. These tasks will be reassigned to the new node, while the mapping relationship between most other tasks on the ring and the printer remains unchanged, thus minimizing the impact of remapping. (6) Introducing virtual nodes: In order to avoid uneven distribution of printer nodes on the ring and resulting in load skew, multiple virtual nodes are generated for each physical printer node and these virtual nodes are mapped to different positions on the ring; by increasing the number of virtual nodes, the task distribution can be more even and better load balancing can be achieved.
8. The intelligent layout and optimized printing method for OA approval documents based on a dynamic template engine according to claim 1, characterized in that, In step S7, resource allocation adopts a dynamic allocation architecture. The resource reallocation based on Q-learning is achieved through the following steps: (1) Define the state space: The system state is composed of key resource indicators; (2) Define the action space: The actions that the agent can perform represent the redistribution decision; (3) Design the reward function: The reward function is used to evaluate the quality of the action and guide the agent to learn the optimal strategy; (4) Construct and update the Q table.
Citation Information
Patent Citations
Custom printing method and device, computer equipment and medium
CN112214184A