Home > Software design >  How to render html in backend and save to pdf?
How to render html in backend and save to pdf?

Time:01-31

I am creating a document for my users that is prefilled/customized with each user's information, and I would like to save a copy of the document to my database/filesystem.

To show the contract to the user, in the frontend I have a React page with a few blanks. I pull info from the backend to fill in those blanks, and I allow the user to print the finished document out. I would like to save a pdf for myself in the backend too, though, and I'm not sure how to do it.

Is it possible to render and populate React in my backend and convert that into a pdf, all in the backend?

I've tried Googling different solutions, but I haven't found anything helpful.

CodePudding user response:

use headless browser, such as puppeteer:

const puppeteer = require('puppeteer')

async function printPDF(url) {
  const browser = await puppeteer.launch({ headless: true })
  const page = await browser.newPage()
  await page.goto(url)
  const pdf = await page.pdf({ format: 'A4' })
  await browser.close()
  return pdf
}

CodePudding user response:

depending on what programming languague is your BE using, you can likely follow these steps with the proper library:

  • On the BE you should have access to your customer information already as you're sending it to FE.
  • With this information use a template system to render the variables to the HTML code, you may need to edit your react code a little to match the template scheme.
  • Then with the render template use a library to generate a PDF file and save it to the proper place (depending on your architecture, eg: on a folder on the same system, an s3 bucket, etc).
  • Finally after saving the pdf and getting the URL, save the string URL to your user table if any.

For example, in python you can use the following libs:

jinja (template renderer) pdfkit (html pdf renderer)

  • Related