【问题标题】:React JS + PDFKit反应 JS + PDFKit
【发布时间】:2019-11-11 09:39:39
【问题描述】:

我试图了解如何让 PDF Kit 在 React JS 中工作。

我的简单要求是使用 ReactJS 和 PDFKit 在浏览器中呈现文件。

查看教程,有一些关于 PDFKit 可以在浏览器中工作的选项的参考资料,但是目前尚不清楚这将如何应用于 React JS 的世界,特别是基于 Create React App 的项目......

http://pdfkit.org/demo/browser.html

https://www.npmjs.com/package/pdfkit#browser-usage

有没有人遇到过基于 React JS 和 PDFKit 的 Create React App 的工作示例?

Google 今天晚上的答案似乎有点不足。

【问题讨论】:

  • 我在同一条船上,我找不到有关如何在 React 项目中实现它的文档。
  • 如果您使用的是 webpack,显然这可以通过使用名为“transform-loader”的包来实现

标签: reactjs create-react-app pdfkit


【解决方案1】:

我想做到这一点(使用 create-react-app 引导的 React 应用程序中的 PdfKit 客户端渲染)。我设法使用pdfkit-webpack-example 和customize-cra 让它工作。

Source

Live Demo

【讨论】:

    【解决方案2】:

    我设法找到了答案。

    它是this 和this 的组合。

    但只是为了提供概述/关键代码。在我的反应应用程序中,我有这个(向我的 API 服务器发出发布请求):

                <Button
                  onClick={(e) => {
                    const { _id } = record;
                    fetch(`/api/pdf`, {
                      method: 'POST',
                      headers: {
                        'Content-Type': 'application/json',
                      },
                      body: JSON.stringify({
                        filename: "test",
                        content: "Testing Content"
                      }),
                    }).then(async res => {
                      if (res.status === 200) {
                        const blob = await res.blob();
                        const file = new Blob(
                          [blob], 
                          {type: 'application/pdf'}
                        );
                        //Build a URL from the file
                        const fileURL = URL.createObjectURL(file);
                        //Open the URL on new Window
                        window.open(fileURL);  
                      }
                    })
                >    
                  Download
                </Button>
    

    在 API 服务器(节点快速应用程序)中,我有这个:

    const postMethod = () => async (req, res, next) => {
       const doc = new PDFDocument()
       let filename = req.body.filename
       // Stripping special characters
       filename = encodeURIComponent(filename) + '.pdf'
       // Setting response to 'attachment' (download).
       // If you use 'inline' here it will automatically open the PDF
       res.setHeader('Content-disposition', 'attachment; filename="' + filename + '"')
       res.setHeader('Content-type', 'application/pdf')
       const content = req.body.content
       doc.y = 300
       doc.text(content, 50, 50)
       doc.pipe(res)
       doc.end()
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-08
      • 2015-08-20
      • 2020-03-15
      • 2022-12-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多