Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading