📌  相关文章
📜  在新选项卡中反应打开 pdf - Javascript 代码示例

📅  最后修改于: 2022-03-11 15:03:49.883000             🧑  作者: Mango

代码示例2
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 (
      
    {names.map((row, index) => { return (
  • {row}

  • ) })}
) } 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 ( ) } export default GeneratePDF