簡體   English   中英

如何使用 Nest js 作為服務器端並在客戶端反應從 puppeteer 下載 pdf?

[英]How to download pdf from puppeteer using Nest js as Server Side and React in Client Side?

我在后端使用 Nest 使用 Puppeteer 生成 pdf 文件。 當我給它提供在磁盤上創建 pdf 的路徑時,Puppeteer 工作正常。

我目前正在退回 pdf。

這是生成 pdf 的代碼:

const browser = await puppeteer.launch({ headless: true });
    const page = await browser.newPage();
    await page.goto('https://blog.risingstack.com', {waitUntil: 'networkidle0'});


    var options = {
      width: '1230px',
      displayHeaderFooter: false,
      margin: {
        top: "10px",
        bottom: "30px"
      },
      printBackground: true,
    }

    const pdf = await page.pdf(options);
  
    await browser.close();
    return pdf

這是調用前面的function的controller:

  @Header('Content-Type', 'application/pdf')
  async Printpdf(@Body() message: any) {
    console.log(message);
    return this.PrintpdfService.printpdf();
  }

在 React 中,我使用 axios 來調用它,如下所示:

return axios.post(`http://localhost:3000/printpdf`,data, {
    responseType: 'arraybuffer',
    headers: {
      'Accept': 'application/pdf'
    }
  });

我正在嘗試使用以下命令下載 pdf:

getBuildingReport(data).then((response) => {
      console.log(response);
      const blob = new Blob([response.data], {type: 'application/pdf'})
       const link = document.createElement('a')
       link.href = window.URL.createObjectURL(blob)
       link.download = `name.pdf`
       link.click();
    })
    .catch(err => {
      console.log(err)
    }); 

我按照本教程進行操作。 https://blog.risingstack.com/pdf-from-html-node-js-puppeteer/#option3

但下載的 pdf 構建正確,無法打開它,因為我得到“加載 PDF 文檔失敗”。

我曾經為一個項目解決了這個問題並保存了代碼片段......關鍵是將 PDF 加載到緩沖區中,然后將其發送回客戶端。

這是在 NestJS 服務中實現的示例 function:

  async generatePDF(): Promise<Buffer> {
    const content = fs.readFileSync(
      path.resolve(__dirname, './templates/invoice.html'),
      'utf-8'
    )

    const browser = await puppeteer.launch({ headless: true })
    const page = await browser.newPage()
    await page.setContent(content)

    const buffer = await page.pdf({
      format: 'A4',
      printBackground: true,
      margin: {
        left: '0px',
        top: '0px',
        right: '0px',
        bottom: '0px'
      }
    })

    await browser.close()

    return buffer
  }

這是一個示例 NestJS controller:

  @Get('/:uuid/pdf')
  async getInvoicePdfByUUID(
    @Param('uuid', ParseUUIDPipe) uuid: string,
    @GetUser() user: User,
    @Res() res: Response,
  ): Promise<void> {

    // ...

    const buffer = await this.invoicesService.generatePDF()

    res.set({
      // pdf
      'Content-Type': 'application/pdf',
      'Content-Disposition': 'attachment; filename=invoice.pdf',
      'Content-Length': buffer.length,

      // prevent cache
      'Cache-Control': 'no-cache, no-store, must-revalidate',
      'Pragma': 'no-cache',
      'Expires': 0,
    })

    res.end(buffer)
  }

請注意,以上假設您將 NestJS 與 Express 一起使用。

干杯!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM