react open pdf in new tab

Solutions on MaxInterview for react open pdf in new tab by the best coders in the world

showing results for - "react open pdf in new tab"
Giulio
31 Jul 2018
1<a href='/api/v1/print/example.pdf' target='_blank' rel='noopener noreferrer'>
2
Sofia
03 May 2018
1Server:________________________________________
2
3const express = require('express')
4const router = express.Router()
5
6const puppeteer = require('puppeteer')
7
8const generatePDF = async (html = '') => {
9  const browser = await puppeteer.launch()
10  const page = await browser.newPage()
11  await page.setContent(html, { waitUntil: 'networkidle0' })
12  const pdfBuffer = await page.pdf({ format: 'a4' })
13
14  await page.close()
15  await browser.close()
16
17  return pdfBuffer
18}
19
20router.post('/', async (req, res) => {
21  // console.log(req.body)
22  const pdf = await generatePDF(req.body.html)
23  // res.contentType('application/pdf')
24  res.set({ 'Content-Type': 'application/pdf', 'Content-Length': pdf.length })
25  res.send(pdf)
26})
27
28module.exports = router
29
30Client:___________________________________________________
31
32const GeneratePDF = () => {
33const names = ['John', 'Alexander', ' Alex', 'Allan', 'Jacob']
34
35  const renderRows = (names) => {
36    return (
37      <ul>
38        {names.map((row, index) => {
39          return (
40            <li key={index}>
41              <p>{row}</p>
42            </li>
43          )
44        })}
45      </ul>
46    )
47  }
48
49  const pdfClickHandler = async () => {
50    const html = ReactDOMServer.renderToStaticMarkup(renderRows(names))
51    try {
52      const response = await axios.post(
53        '/api/services/pdf',
54        { html },
55        {
56          responseType: 'arraybuffer',
57          headers: {
58            Accept: 'application/pdf',
59          },
60        }
61      )
62
63      const file = new Blob([response.data], { type: 'application/pdf' })
64
65      const fileURL = URL.createObjectURL(file)
66
67      const pdfWindow = window.open()
68
69      pdfWindow.location.href = fileURL
70
71    } catch (err) {
72      console.log(err.messaes)
73    }
74  }
75
76  return (  
77      <Button variant='contained' onClick={pdfClickHandler}>
78        Generate PDF
79      </Button>
80  )
81}
82
83export default GeneratePDF