Build PDF Documents with React on the Server

  • What approach to use for PDF generation?
  • How to manage the page breaks?
  • Is it possible to have the final document preview immediately?
  • Do we need to have a Java/C#/Python or any other language-based server or can we do it with JavaScript?
  • Should we consider some third-party solution and whether it fulfills all our requirements?
  • Maybe it should be on the Front End (client) side instead of the Back End?

Questions need to be answered first

Where to start?

Brief:

Step one: Project structure

Project folders structure

Step two: Setup basic Web UI layout

Step three: Basic report components setup

Base block abstract class
Title block implementation
  1. The layout of the report can be constructed dynamically.
  2. We can consume schema not only in our service but, maybe, on the other service built with different programming languages, in case, we will need to support that in prospect.
  3. Schema can be stored in the database as a simple JSON and transferred over the network easily.
  4. We create a restricted set of supported blocks, so no magic here. It also helps to avoid vague product requirements.
  5. Scoped implementation, preventing chaotic code structures that are unreadable.
Component to render the Schema
Example of the Schema

Step three: Data provider

Data provider code
Passing unknown accessor error

Step four: Set up the server-side

  1. Accept the Schema and Data through the REST (no necessarily) API
  2. Parse the body and validate it. (Check for unknown identifiers, etc)
  3. Deserialize Schema JSON into actual block instances
  4. Feed the Schema to the RenderBlock component and Data to DataProvider component
  5. Render everything to the HTML string (or stream). Optionally include the necessary CSS code
  6. Sanitize the HTML result to cover the security risks
  7. Using Puppeteer render HTML in the headless Chrome and extract PDF file with the supported API
  8. Push PDF file as a stream to the client in the HTTP response
PDF controller with validation
PDF service with deserialization
HTML generation
HTML to PDF conversion

Step five: connect UI and Shared component

Rendering instant preview of the PDF
Data payload creation

Step six: connect UI and Service

HTTP Request to the PDF service

Conclusion:

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store