首页 > 解决方案 > 在节点js中将html表单转换为pdf?

问题描述

我创建了一个将 HTML 文件转换为 pdf 的类。下面是代码

class Invoice {  
  async html() {
    try {
      const data = {
        your: 'data'
      }
      console.log("Current directory:", __dirname); 

      const templatePath = Path.resolve('index.html')
      console.log(templatePath)
      const content = await ReadFile(templatePath, 'utf8')
      // compile and render the template with handlebars
      const template = Handlebars.compile(content)
      return template(data)
    } catch (error) {
      throw new Error('Cannot create invoice HTML template.')
    }
  }

  async pdf() {
    const html = await this.html()
    console.log(html)
    const browser = await Puppeteer.launch()
    const page = await browser.newPage()
    await page.setContent(html)
    return page.pdf()
  }
}

但这会读取位于磁盘上的 HTML 文件。但我想在 html 文件中创建 HTML 表单的 pdf。

请告诉我我该怎么做?

标签: javascriptnode.jspdfpuppeteer

解决方案


你试过jsPDF吗?根据他们的网站,jsPDF 是用于生成 PDF 的领先 HTML5 客户端解决方案。非常适合活动门票、报告和证书。


推荐阅读