Kea*_*tor 5 pdfkit reactjs create-react-app
我试图了解如何让 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 的工作示例?
谷歌今晚似乎没有给出答案。
小智 2
我设法找到这个问题的答案。
但只是给出概述/关键代码。在我的 React 应用程序中,我有这个(向我的 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>
Run Code Online (Sandbox Code Playgroud)
在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()
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
8033 次 |
| 最近记录: |