reaja o pdf aberto na nova guia
<a href='/api/v1/print/example.pdf' target='_blank' rel='noopener noreferrer'>
Crowded Copperhead
<a href='/api/v1/print/example.pdf' target='_blank' rel='noopener noreferrer'>
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