简体   繁体   English

如何在后端渲染html并保存到pdf?

[英]How to render html in backend and save to pdf?

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 document to the user, in the frontend I have a React page with a few blanks.为了向用户显示文档,在前端我有一个带有一些空白的 React 页面。 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.不过,我也想在后端为自己保存一个 pdf,但我不确定该怎么做。

Is it possible to render and populate React in my backend and convert that into a pdf, all in the backend?是否可以在我的后端渲染和填充 React 并将其转换为 pdf,全部在后端?

I've tried Googling different solutions, but I haven't found anything helpful.我试过谷歌搜索不同的解决方案,但没有发现任何有用的信息。

use headless browser, such as puppeteer:使用无头浏览器,例如 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
}

depending on what programming languague is your BE using, you can likely follow these steps with the proper library:根据您的 BE 使用的编程语言,您可能可以使用适当的库执行以下步骤:

  • On the BE you should have access to your customer information already as you're sending it to FE.在 BE 上,您应该已经可以访问您的客户信息,因为您正在将其发送给 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.使用此信息使用模板系统将变量呈现为 HTML 代码,您可能需要稍微编辑您的 React 代码以匹配模板方案。
  • 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).然后使用渲染模板使用库生成 PDF 文件并将其保存到适当的位置(取决于您的体系结构,例如:同一系统上的文件夹、s3 存储桶等)。
  • Finally after saving the pdf and getting the URL, save the string URL to your user table if any.最后在保存 pdf 并获得 URL 后,将字符串 URL 保存到您的用户表(如果有)。

For example, in python you can use the following libs:例如,在 python 中,您可以使用以下库:

jinja (template renderer) pdfkit (html pdf renderer) jinja(模板渲染器)pdfkit(html pdf 渲染器)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM