Search code examples
node.jsreact-pdf

How to use @react-pdf/renderer in backend nodeJs with Images and fonts


I have a nodeJs application, i want to create pdf in backend using @react-pdf/renderer library. My pdf contains images and external fonts. is there any way to do that? Thanks in Advance..


Solution

  • Since you are using @react-pdf/renderer you need to install react in nodejs. So you should have es6 support.

    For that install these packages

    "@babel/core": "^7.12.17",
    "@babel/preset-env": "^7.12.17",
    "@babel/preset-react": "^7.16.5",
    "babel-cli": "^6.26.0",
    "babel-plugin-transform-runtime": "^6.23.0",
    "babel-preset-stage-0": "^6.24.1",
    "babel-runtime": "^6.26.0",
    

    Create a .babelrc file with this contents

    {
      "presets": [
        "@babel/preset-env",
        "@babel/preset-react"
      ],
      "plugins": [
        [
          "@babel/transform-runtime"
        ]
      ]
    }
    

    Your script should look like

    "scripts": {
        "start": "node dist/index.js", # Your Path 
        "dev": "babel-node src/index.js", # Your Path 
        "build": "babel src -d dist", # If using build
      },
    
    

    Once you are done configuring this You can use @react-pdf/renderer as follows

    import React from 'react';
    import ReactPDF from '@react-pdf/renderer';
    
    const pdfStream = await ReactPDF.renderToStream(<MyDocument />);
    res.setHeader('Content-Type', 'application/pdf');
    pdfStream.pipe(res);
    pdfStream.on('end', () => console.log('Done streaming, response sent.'));
    

    For more details refer https://react-pdf.org/advanced#usage-with-express.js