问题描述
我正在 NodeJS 后端使用 html-pdf-node
生成 PDF 文件。
exports.generatePDF = async (req,res,next) => {
const data = req.body || req.body.data;
const content = data.html;
let options = {
format: 'letter',margin: {
right: '40px',left: '40px'
}
};
let file = { content };
html_to_pdf.generatePdf(file,options).then(pdfBuffer => {
res.setHeader('Content-Length',pdfBuffer.length);
res.setHeader('Content-Type','application/pdf');
return res.end(pdfBuffer);
});
}
然后,我尝试使用 react-pdf
在 React 中打开生成的 PDF。
import React,{ useState,useEffect } from 'react';
import { Document } from 'react-pdf';
import * as helperAPI from '../../api/Helper'; // This is just a helper for the axios request to NodeJS
const PDFViewer = (props) => {
//const html = props.html;
const html = "<html><body><div><p>This is a Test</p></div></body></html>";
const [ pdfLink,setPDFLink ] = useState(null);
useEffect(() => {
async function fetchData() {
const res = await helperAPI.generatePDF({html});
const file = new Blob(
[res],{type: 'application/pdf'}
);
const fileURL = URL.createObjectURL(file);
setPDFLink(fileURL);
}
fetchData();
},[html]);
const onDocumentLoadSuccess = () => {
console.log('onLoad');
console.log(pdfLink);
}
console.log('Link: ' + pdfLink);
return (
<div>
<Document
file={{
url: pdfLink,}}
onLoadSuccess={onDocumentLoadSuccess}
/>
</div>
);
}
export default PDFViewer;
helperAPI 中的 axios 请求:
import axios from 'axios';
import * as url from '../Constants/Custom';
export const generatePDF = async (data) => {
let output = "";
await axios.post(`${url.REQ_URL}/helper/generatePDF`,data)
.then((res) => {
output = res.data;
});
return output;
};
当我运行代码时,浏览器返回:Failed to load PDF file.
如何从 react-pdf
中的 NodeJS 加载 blob 生成的文件?
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)