Method for converting real-time webpage data into PDF (Portable Document Format) file
By combining the nonsensical mode of the APP server and the Chrome browser, the performance bottleneck and compatibility issues of HTML to PDF conversion in the existing technology are solved, real-time and highly compatible web page to PDF conversion is achieved, and the conversion efficiency and users are improved. experience.
Patent Information
- Application Number
- CN202410879979.8
- Authority / Receiving Office
- CN · China
- Patent Type
- Applications(China)
- Current Assignee / Owner
- Filing Date
- 2024-07-02
- Publication Date
- 2024-09-24
AI Technical Summary
The existing technology has problems such as performance bottlenecks, failure in complex style conversion, inability to support responsive layout, and the need to generate static HTML during the conversion process of HTML to PDF, making it impossible to achieve real-time HTML conversion.
Combined with the APP server and Chrome browser, by setting the nonsensical mode, using the Page.printToPDF function to render web pages into PDF, and processing web page conversion requests on the server side, it supports asynchronous processing and load balancing to ensure efficiency and compatibility.
It realizes the conversion of real-time web page data to PDF, maintains high compatibility and high fidelity, reduces system resource consumption, improves conversion efficiency, ensures security and cross-platform performance, and supports automated and customized output.
Smart Images

Figure CN118690726A
Abstract
Description
Technical Field
[0001] The present invention relates to the technical field of web page processing applications, and in particular to a method for converting web page data into a PDF file in real time, and is particularly suitable for the application field of converting any site web page into a PDF file in real time. Background Art
[0002] At present, in the Java technology stack, there are two commonly used technical solutions for converting HTML to PDF in the industry: itext and wkhtmltopdf. Itext is the most widely used PDF tool under the Apache organization, but it has a large performance bottleneck and will fail to convert when encountering complex styles. wkhtmltopdf is an open source framework on GitHub, with better performance than itext and can also convert complex styles well, but it needs to rely on third-party components and does not support responsive layout in HTML.
[0003] Another common problem of the above two frameworks is that they need to generate static HTML with inline styles before conversion, which makes real-time HTML conversion impossible.
[0004] Therefore, based on the existing technology stack, how to solve this problem of users is a technical issue worthy of attention.
[0005] When thinking about this problem, the applicant found that most mobile Internet websites are responsive layout web pages based on react technology, which are perfectly compatible with chrome kernel browser access. If the ability of chrome kernel API can be used to convert PDF, it will perfectly solve the difficult technical problems such as performance, complex styles, responsive layout, etc., making html to pdf very valuable. Summary of the invention
[0006] In order to solve the common problems in the conversion process of the prior art, such as memory overflow, font problems, image problems, security problems, performance problems, etc., the purpose of the present invention is to provide a method for converting web page data into PDF files in real time. The invention combines the functions of the APP server and the Chrome browser to realize an effective method for converting web page data into PDF files in real time.
[0007] The present invention achieves the above-mentioned purpose through the following technical solutions:
[0008] A method for converting real-time web page data into a PDF file, the method comprising the following steps:
[0009] Deploy the web page URL corresponding to the developed web page data to the site provided by the APP server to ensure that the web page can be accessed through the public URL;
[0010] Submit a PDF conversion request, and send the PDF conversion request containing the target webpage URL to the APP server;
[0011] After the APP server receives the PDF conversion request, it checks whether the Chrome browser has been downloaded locally;
[0012] If the Chrome browser exists locally, set the Chrome nonsensical mode and configure the browser parameters to adapt to the header construction required for PDF generation;
[0013] Specify the storage path of the PDF file, call the Page.printToPDF function of the Chrome browser to render the target web page as a PDF file, and send the PDF file to the APP client.
[0014] According to a method for converting real-time web page data into a PDF file provided by the present invention, if the Chrome browser is not downloaded locally, the installation package is downloaded according to a preset network address and installed to a specified location.
[0015] According to a method for converting real-time web page data into a PDF file provided by the present invention, when setting the Chrome nonsense mode, a Puppeteer proxy is created; a parameter object for browser startup is set; a Chrome extractor object is created; the Chrome extractor object is passed into the parameter object for browser startup to create a browser object; and Target.createTarge is sent to obtain the web page object created in the browser.
[0016] According to a method for converting real-time web page data into a PDF file provided by the present invention, when a Chrome browser object is successfully created, a browser context ID is set, and the Target.createTarget method function in Chrome is called to obtain the web page object created in the browser;
[0017] Based on the web page object created in the browser, navigate to the HTML web page address that needs to be converted and wait for the browser navigation to complete.
[0018] According to a method for converting real-time web page data into a PDF file provided by the present invention, when waiting for browser navigation to complete, the results of the stages of waiting for navigation are load event triggering->domcontentloaded event triggering->newworkidle0 event triggering->networkidle2 event triggering in sequence.
[0019] According to a method for converting real-time web page data into a PDF file provided by the present invention, PDF conversion parameters are set after the web page is successfully created;
[0020] After creating the PDF file storage path, pass the path to the created web page object;
[0021] Call the Chrome browser Page.printToPDF function to perform PDF conversion.
[0022] According to a method for converting real-time web page data into a PDF file provided by the present invention, the PDF conversion parameters include converting the PDF width and height, the upper and lower left and right spacing, the conversion model, whether to convert to a horizontal screen, hide the header and footer, the header template, the footer template, whether to print behind, the scaling ratio, specifying the PDF file in the page range, specifying the preferred CSS page size, the production range, and the page number range.
[0023] According to a method for converting real-time web page data into a PDF file provided by the present invention, before executing the PDF conversion, the cache of the Chrome browser is cleared to ensure that the latest web page content is obtained from the server every time.
[0024] According to a method for converting real-time web page data into a PDF file provided by the present invention, the following steps are further performed:
[0025] Before starting PDF conversion, first check the network connection status of the device to ensure that the network is stable and meets the conversion requirements, and add network exception capture logic. When a network error occurs, automatically retry a certain number of times to improve the conversion success rate.
[0026] According to a method for converting real-time web page data into a PDF file provided by the present invention, the following steps are further performed:
[0027] When the number of PDF conversion requests is large, the time-consuming PDF conversion operation is put into the background and processed asynchronously using a message queue or task queue.
[0028] Among them, one or more message queues or task queues are created to manage PDF conversion tasks;
[0029] Use priority queues to ensure that important or urgent conversion tasks are processed first;
[0030] Monitor server load and queue length in real time to detect potential overload issues in a timely manner;
[0031] If you find that the server load is too high or the queue length is too long, increase server resources or use load balancing technology to distribute requests to multiple servers.
[0032] It can be seen that compared with the prior art, the present invention has the following beneficial effects:
[0033] 1. Real-time: Since the conversion process occurs on the server side, users can submit the webpage URL in real time and get the corresponding PDF file immediately without waiting for a long time for processing or rendering;
[0034] 2. Compatibility: Using the Chrome browser for rendering and conversion ensures that web content maintains high compatibility when converted to PDF, because Chrome supports a variety of web standards and formats;
[0035] 3. Headless Mode: By setting Chrome's Headless Mode, you can run the browser without a graphical interface, which greatly reduces the consumption of system resources and improves conversion efficiency;
[0036] 4. Flexibility: By configuring browser parameters, you can make specific settings for PDF generation, such as headers and footers, page margins, paper size, etc., so as to generate PDF files that meet your needs;
[0037] 5. High fidelity: Since the Chrome browser is used directly for rendering, the converted PDF file can better retain the style, layout and interactive elements of the original web page, ensuring high fidelity of the conversion;
[0038] 6. Automation: The entire conversion process can be completed automatically on the server side without manual operation by the user, which greatly improves work efficiency;
[0039] 7. Scalability: This method can be easily integrated into existing apps or systems. By providing an API interface, other apps or services can also easily call the conversion function.
[0040] 8. Security: By controlling the PDF conversion process through the APP server, the security of user data can be better protected and the risks that may be caused by sensitive operations on the client can be avoided;
[0041] 9. Cross-platform: Since the Chrome browser supports multiple operating systems, this method can realize the conversion of web pages to PDF on different platforms and has good cross-platform performance;
[0042] 10. Customizability: The output format, resolution, color mode and other parameters of the PDF file can be customized according to specific needs to meet the usage requirements in different scenarios.
[0043] 11. Improve web page rendering speed: The styles in the web page can be reused, and there is no need to write inline styles, which will not cause bloated code. The lightweight and concise web page rendering speed is greatly improved to improve the user experience.
[0044] 12. There is no requirement for CPU when converting PDF. In the mobile Internet, front-end engineers do not need to write two web pages to adapt to PC and mobile styles.
[0045] The present invention is further described in detail below in conjunction with the accompanying drawings and specific embodiments. BRIEF DESCRIPTION OF THE DRAWINGS
[0046] Figure 1 The present invention is a flowchart of a method for converting web page data into a PDF file in real time.
[0047] Figure 2 It is a download flow chart of the Chrome browser in an embodiment of a method for converting real-time web page data into a PDF file of the present invention.
[0048] Figure 3 This is a flow chart about creating a Chrome browser object in an embodiment of a method for converting real-time web page data into a PDF file of the present invention.
[0049] Figure 4 It is a flow chart of creating a new web page object in a Chrome browser in an embodiment of a method for converting real-time web page data into a PDF file of the present invention.
[0050] Figure 5 It is a flow chart about creating PDF parameters in an embodiment of a method for converting real-time web page data into a PDF file of the present invention. DETAILED DESCRIPTION
[0051] In order to make the purpose, technical solution and advantages of the present invention clearer, the technical solution of the present invention will be clearly and completely described below in conjunction with the drawings of the present invention. Obviously, the described embodiments are part of the embodiments of the present invention, not all of the embodiments. Based on the embodiments of the present invention, all other embodiments obtained by ordinary technicians in this field without creative work are within the scope of protection of the present invention.
[0052] Reference to "embodiments" herein means that a particular feature, structure, or characteristic described in conjunction with the embodiments may be included in at least one embodiment of the present application. The appearance of the phrase in various locations in the specification does not necessarily refer to the same embodiment, nor is it an independent or alternative embodiment that is mutually exclusive with other embodiments. It is explicitly and implicitly understood by those skilled in the art that the embodiments described herein may be combined with other embodiments.
[0053] See also Figures 1 to 5 The present invention provides a method for converting real-time web page data into a PDF file, the method comprising the following steps:
[0054] Step S1, deploying the webpage URL corresponding to the developed webpage data to the site provided by the APP server to ensure that the webpage can be accessed through the public URL;
[0055] Step S2, submitting a PDF conversion request, and sending the PDF conversion request including the target webpage URL to the APP server;
[0056] Step S3, after the APP server receives the PDF conversion request, it checks whether the Chrome browser has been downloaded locally;
[0057] Step S4, if a Chrome browser exists locally, set the Chrome nonsensical mode and configure browser parameters to adapt to the header construction required for PDF generation;
[0058] Step S5, specify the storage path of the PDF file, call the Page.printToPDF function of the Chrome browser to render the target web page as a PDF file, and send the PDF file to the APP client.
[0059] In the above step S3, if the Chrome browser is not downloaded locally, the installation package is downloaded according to the preset network address and installed to the specified location.
[0060] In the above step S4, when setting the chrome nonsense mode, create a Puppeteer proxy; set the parameter object for browser startup; create a chrome extractor object; pass the chrome extractor object into the parameter object for browser startup to create a browser object; send Target.createTarge to obtain the web page object created in the browser.
[0061] When the Chrome browser object is created successfully, set the browser context ID and call the Target.createTarget method function in Chrome to obtain the web page object created in the browser;
[0062] Based on the web page object created in the browser, navigate to the HTML web page address that needs to be converted and wait for the browser navigation to complete.
[0063] While waiting for the browser navigation to complete, the results of the waiting navigation stages are load event triggering -> domcontentloaded event triggering -> newworkidle0 event triggering -> networkidle2 event triggering.
[0064] load: Wait for the load event on the page to fire, which usually means that all resources on the page (including images, style sheets, and scripts) have finished loading. However, since some scripts may continue to run after the load event is fired, this is not the best indicator that the page is "fully" loaded.
[0065] domcontentloaded: Wait for the DOMContentLoaded event to fire, which means that the HTML document has been fully loaded and parsed without waiting for style sheets, images, and subframes to finish loading. At this point, you can safely run scripts that depend on the DOM.
[0066] NetworkIdle0: Waits for at least 500 milliseconds, then checks if there has been no network activity on the network connection for at least 500 milliseconds, which usually means that the page has completed the main network request, but may still be loading some secondary resources. NetworkIdle0 is a good compromise because it allows the page to load some additional resources while ensuring that the main rendering work has been completed.
[0067] networkidle2: Similar to 'networkidle0', but only triggered when there has been no network activity on the connection for at least 2 seconds. This provides a stricter waiting condition, ensuring that more resources have been loaded.
[0068] In this embodiment, when the web page is successfully created, the PDF conversion parameters are set, and after the PDF file storage path is created, the path is passed to the created web page object, and the chrome browser Page.printToPDF function is called to perform PDF conversion.
[0069] Among them, PDF conversion parameters include converting PDF width and height, top, bottom, left, and right spacing, conversion model, whether to display horizontally, hiding header and footer, header template, footer template, whether to print behind, scaling, specifying the page range of the PDF file, specifying the preferred CSS page size, production range, and page number range.
[0070] In this embodiment, before performing PDF conversion, the cache of the Chrome browser is cleared to ensure that the latest web page content is obtained from the server each time, which helps to avoid problems caused by cache when performing PDF conversion.
[0071] In this embodiment, before starting the PDF conversion, the network connection status of the device is first checked to ensure that the network is stable and meets the conversion requirements, and the capture logic of the network exception is added, such as using a try-catch statement to capture possible network errors. When a network error occurs, it automatically retries a certain number of times to improve the conversion success rate. When a network error is captured, a corresponding error prompt can be given, such as "Network connection failed, please check your network connection", etc., and the user is allowed to retry the conversion or select other operations.
[0072] In this embodiment, when the number of PDF conversion requests is large, the time-consuming PDF conversion operation is put into the background and processed asynchronously using a message queue or a task queue; one or more message queues or task queues are created to manage PDF conversion tasks; a priority queue is used to ensure that important or urgent conversion tasks are processed first; the server load and queue length are monitored in real time to promptly detect potential overload problems; if the server load is found to be too high or the queue length is too long, server resources are increased or load balancing technology is used to distribute requests to multiple servers.
[0073] Specifically, the system provided in this embodiment consists of three parts: APP web page, APP server, and Chrome browser. Among them, APP web page is the application in the user APP, APP server is the backend server system that provides service sites for the application in the APP, and the Chrome browser is a third-party tool. This embodiment completes the specified goal through the collaboration of APP web page, APP server, and third-party Chrome.
[0074] In practical applications, this embodiment is based on the real-time generation of PDF from the "Assisted Decision System" plan webpage as an example. Among them, "Assisted Decision" is a rescue system that provides a real-time plan solution for actual fire disaster rescue.
[0075] Specifically, the components in the corresponding invention in this example include: APP web page, hereinafter referred to as gzbfj Page; APP server, hereinafter referred to as gzbfj Server; third-party Chrome is the chromium component provided by Google, hereinafter referred to as Chrome;
[0076] The specific example working process includes the following steps:
[0077] The user opens the gzbfj page and clicks the forward button on the page. The gzbfj page is an example of a certain business system, which only uses the webpage to PDF function provided by the present invention. The present invention supports the use of any business system.
[0078] After receiving the forwarding request, gzbfj Server first determines whether the PDF has been generated. If not, it generates the PDF.
[0079] First, determine whether Chrome has been downloaded in this gzbfj server. If not, download it immediately. Figure 2 As shown. Each time you execute the html to pdf conversion, first check whether there is a chrome browser installation package in the specified location. If there is, skip downloading. If not, go to the specified network address to download the chrome installation package to this location.
[0080] Set the Chrome nonsensical mode, create the PUPPETEER proxy, set the system parameters, create the Chrome extractor object, pass the extractor object into the browser parameter object to create the browser object, and finally send the Chrome command Target.setDiscoverTargets to get the browser to create the object stream, such as Figure 3 shown.
[0081] Among them, the nonsensical modes no-sandbox and disable-setuid-sandbox are set. The purpose is to run Chromium and Chrome applications without Sandbox. disable-setui-sandbox is to disable the setuid sandbox (Linux only). Create a Puppeteer object, which is an open source framework in the industry to control the Chrome browser, and then launch the nonsensical configuration. Then set the browser startup parameters user-data-dir, auto-open-devtools-for-tabs, headless, hide-scrollbars, mute-autio, about: blank, etc., and then find the first step of the Chrome download location to execute and start a debug mode browser entity to return.
[0082] Next, based on the started browser entity, set the browserContextId context ID, set the url to the about:blank parameter, and call the Target.createTarget method function in chrome to create a new page entity and return it.
[0083] Then, based on the created page entity, navigate to the HTML webpage address to be converted and wait for the browser navigation to complete. The results of the intermediate waiting for navigation are load->domcontentloaded->newworkidle0->networkidle2.
[0084] Next, create a PDF file storage path, set it to the created page entity, set the converted PDF width and height, top and bottom, left and right spacing, transferMode (conversion model is ReturnAsStream), landscape (whether horizontal screen), displayHeaderFooter (hide header and footer), headerTemplate (header template), footerTemplate (footer template), printBackground (whether to print behind), scale (scaling ratio), pageRanges (specify the pdf file in the page range), performCSSPageSize (specify the preferred CSS page size) parameters, call the chrome browser Page.printToPDF function to perform PDF conversion.
[0085] After the Chrome browser object is created successfully, set the browser context ID, and then send Target.createTarget to obtain the web page object stream created in the browser, such as Figure 4 shown.
[0086] When the web page is created successfully, set the PDF parameters, set the necessary parameters for PDF conversion, and send the command Page.printToPDF to convert and generate a PDF file, such as Figure 5 shown.
[0087] Finally, after the PDF file is successfully generated, select the user recipient and push the PDF out.
[0088] In summary, since the conversion process of the present invention occurs on the server side, the user can submit the web page URL in real time and immediately obtain the corresponding PDF file without waiting for a long time for processing or rendering; the present invention uses the Chrome browser for rendering and conversion to ensure that the web page content can maintain a high compatibility when converted to PDF, because Chrome supports multiple web page standards and formats.
[0089] The present invention can run the browser without a graphical interface by setting the nonsensical mode of Chrome, which greatly reduces the consumption of system resources and improves the conversion efficiency; the present invention can perform specific settings for PDF generation, such as headers and footers, page margins, paper size, etc., by configuring browser parameters, so as to generate a PDF file that meets the requirements; since the present invention directly uses the Chrome browser for rendering, the converted PDF file can better retain the style, layout and interactive elements of the original web page, thereby ensuring the high fidelity of the conversion.
[0090] The entire conversion process of the present invention can be automatically completed on the server side without manual operation by the user, which greatly improves work efficiency; the present invention can be easily integrated into an existing APP or system, and by providing an API interface, other applications or services can also conveniently call the conversion function; the present invention controls the PDF conversion process through the APP server, which can better protect the security of user data and avoid the risks that may be caused by sensitive operations on the client.
[0091] Since the Chrome browser supports multiple operating systems, the method can realize the conversion of web pages to PDF on different platforms and has good cross-platform performance. The output format, resolution, color mode and other parameters of the PDF file can be customized according to specific needs to meet the usage requirements in different scenarios. The styles in the web pages of the present invention can be reused, and there is no need to write inline styles, which will not cause bloated codes. The lightweight and concise web page rendering speed is greatly improved to improve the user experience. The present invention has no requirements on the CPU when converting PDF, and the front-end engineers in the mobile Internet do not need to write two web pages to adapt to the PC and mobile phone styles.
[0092] The technical features of the above embodiments may be combined arbitrarily. To make the description concise, not all possible combinations of the technical features in the above embodiments are described. However, as long as there is no contradiction in the combination of these technical features, they should be considered to be within the scope of this specification.
[0093] The above-mentioned embodiments are only preferred embodiments of the present invention and cannot be used to limit the scope of protection of the present invention. Any non-substantial changes and substitutions made by technicians in this field on the basis of the present invention shall fall within the scope of protection required by the present invention.
Claims
1. A method for converting real-time web page data into a PDF file, characterized in that: The method comprises the following steps: Deploy the web page URL corresponding to the developed web page data to the site provided by the APP server to ensure that the web page can be accessed through the public URL; Submit a PDF conversion request, and send the PDF conversion request containing the target webpage URL to the APP server; After the APP server receives the PDF conversion request, it checks whether the Chrome browser has been downloaded locally; If the Chrome browser exists locally, set the Chrome nonsensical mode and configure the browser parameters to adapt to the header construction required for PDF generation; Specify the storage path of the PDF file, call the Page.printToPDF function of the Chrome browser to render the target web page as a PDF file, and send the PDF file to the APP client.
2. The method according to claim 1, characterized in that: If the Chrome browser is not downloaded locally, download the installation package according to the preset network address and install it to the specified location.
3. The method according to claim 1, characterized in that: When setting the Chrome nonsense mode, create a Puppeteer proxy; set the parameter object for browser startup; create a Chrome extractor object; pass the Chrome extractor object into the parameter object for browser startup to create a browser object; send Target.createTarge to get the web page object created in the browser.
4. The method according to claim 3, characterized in that: When the Chrome browser object is created successfully, set the browser context ID and call the Target.createTarget method function in Chrome to obtain the web page object created in the browser; Based on the web page object created in the browser, navigate to the HTML web page address that needs to be converted and wait for the browser navigation to complete.
5. The method according to claim 4, characterized in that: While waiting for the browser navigation to complete, the results of the waiting navigation stages are load event triggering -> domcontentloaded event triggering -> newworkidle0 event triggering -> networkidle2 event triggering.
6. The method according to claim 5, characterized in that: When the web page is created successfully, set the PDF conversion parameters; After creating the PDF file storage path, pass the path to the created web page object; Call the Chrome browser Page.printToPDF function to perform PDF conversion.
7. The method according to claim 6, characterized in that: The PDF conversion parameters include converting PDF width and height, top and bottom and left and right spacing, conversion model, whether to be horizontal, hiding header and footer, header template, footer template, whether to print behind, scaling, specifying the PDF file in the page range, specifying the preferred CSS page size, production range and page number range.
8. The method according to any one of claims 1 to 7, characterized in that: Before performing PDF conversion, clear the cache of the Chrome browser to ensure that the latest web page content is obtained from the server every time.
9. The method according to any one of claims 1 to 7, characterized in that: Also execute: Before starting PDF conversion, first check the network connection status of the device to ensure that the network is stable and meets the conversion requirements, and add network exception capture logic. When a network error occurs, automatically retry a certain number of times to improve the conversion success rate.
10. The method according to any one of claims 1 to 7, characterized in that: Also execute: When the number of PDF conversion requests is large, the time-consuming PDF conversion operation is put into the background and processed asynchronously using the message queue or task queue; Among them, one or more message queues or task queues are created to manage PDF conversion tasks; Use priority queues to ensure that important or urgent conversion tasks are processed first; Monitor server load and queue length in real time to detect potential overload issues in a timely manner; If you find that the server load is too high or the queue length is too long, increase server resources or use load balancing technology to distribute requests to multiple servers.
