react open pdf in new tab
<a href='/api/v1/print/example.pdf' target='_blank' rel='noopener noreferrer'>
react open pdf in new tab
<a href='/api/v1/print/example.pdf' target='_blank' rel='noopener noreferrer'>
react open pdf in new tab
Server:________________________________________
const express = require('express')
const router = express.Router()
const puppeteer = require('puppeteer')
const generatePDF = async (html = '') => {
const browser = await puppeteer.launch()
const page = await browser.newPage()
await page.setContent(html, { waitUntil: 'networkidle0' })
const pdfBuffer = await page.pdf({ format: 'a4' })
await page.close()
await browser.close()
return pdfBuffer
}
router.post('/', async (req, res) => {
// console.log(req.body)
const pdf = await generatePDF(req.body.html)
// res.contentType('application/pdf')
res.set({ 'Content-Type': 'application/pdf', 'Content-Length': pdf.length })
res.send(pdf)
})
module.exports = router
Client:___________________________________________________
const GeneratePDF = () => {
const names = ['John', 'Alexander', ' Alex', 'Allan', 'Jacob']
const renderRows = (names) => {
return (
<ul>
{names.map((row, index) => {
return (
<li key={index}>
<p>{row}</p>
</li>
)
})}
</ul>
)
}
const pdfClickHandler = async () => {
const html = ReactDOMServer.renderToStaticMarkup(renderRows(names))
try {
const response = await axios.post(
'/api/services/pdf',
{ html },
{
responseType: 'arraybuffer',
headers: {
Accept: 'application/pdf',
},
}
)
const file = new Blob([response.data], { type: 'application/pdf' })
const fileURL = URL.createObjectURL(file)
const pdfWindow = window.open()
pdfWindow.location.href = fileURL
} catch (err) {
console.log(err.messaes)
}
}
return (
<Button variant='contained' onClick={pdfClickHandler}>
Generate PDF
</Button>
)
}
export default GeneratePDF
Copyright © 2021 Codeinu
Forgot your account's password or having trouble logging into your Account? Don't worry, we'll help you to get back your account. Enter your email address and we'll send you a recovery link to reset your password. If you are experiencing problems resetting your password contact us