Can we print a path-defined pdf using reactjs?

385 views Asked by At

I want to print a pdf file which is obtained from GET request from router.js

router.get('/fetch-pdf',(req,res) => {
  res.sendFile(`${__dirname}/result.pdf`)
})

and my react component is like

App.js

import React from 'react'
import axios from 'axios'
const App = () => {
  handleClick() {
    axios.get('/fetch-pdf').then((res) => {
      // someway to print
    })
  }
  return(
    <button onClick={() => handleClick()}>Click</button>
  )
}
export default APp
1

There are 1 answers

0
crabbly On

I'm assuming your would be using print.js based on the question tag. The library accepts base64 data, therefore, you can just pass that into the printJS function.

Here is one way to get base64 from the axios response data and pass into the lib:

axios.get('/fetch-pdf', {
    responseType: 'arraybuffer'
}).then(res => {
  const buffer = Buffer.from(response.data, 'base64');

  printJS({printable: buffer, type: 'pdf', base64: true})
})

Axios response to base64 ref.

The print.js library does the same when caching pdf files, however it does that without axios. You can see the lib code here if interested: https://github.com/crabbly/Print.js/blob/master/src/js/pdf.js