【问题标题】:Can we print a path-defined pdf using reactjs?我们可以使用 reactjs 打印路径定义的 pdf 吗?
【发布时间】:2020-09-27 00:53:43
【问题描述】:

我想打印一个从 GET 请求中获得的 pdf 文件 router.js

router.get('/fetch-pdf',(req,res) => {
  res.sendFile(`${__dirname}/result.pdf`)
})

我的反应组件就像

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

【问题讨论】:

    标签: node.js reactjs printing printjs


    【解决方案1】:

    我假设您将根据问题标签使用 print.js。该库接受 base64 数据,因此,您只需将其传递给 printJS 函数即可。

    这是从 axios 响应数据中获取 base64 并传入 lib 的一种方法:

    axios.get('/fetch-pdf', {
        responseType: 'arraybuffer'
    }).then(res => {
      const buffer = Buffer.from(response.data, 'base64');
    
      printJS({printable: buffer, type: 'pdf', base64: true})
    })
    

    axios 响应 base64 ref.

    print.js 库在缓存 pdf 文件时执行相同的操作,但是它在没有 axios 的情况下执行此操作。如果有兴趣,您可以在此处查看 lib 代码: https://github.com/crabbly/Print.js/blob/master/src/js/pdf.js

    【讨论】:

      猜你喜欢
      • 2021-11-14
      • 2019-07-05
      • 1970-01-01
      • 2012-07-17
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-19
      • 2023-03-13
      相关资源
      最近更新 更多