0

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 Answer 1

2

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.