reactjs - 使用 react-pdf/renderer 库创建 pdf 客户端
问题描述
我正在创建一个 react web 应用程序,其中必须创建一个下载按钮,该按钮在客户端创建 pdf 并下载 pdf,我正在使用 react-pdf/renderer 库来完成此任务,我已经成功实现了这个示例,我使用了这个库的 PDFDownloadLink 组件,当我将这个库直接渲染到 ReactDOM.render 中时,它工作正常,但是当我尝试在 JSX 元素中使用相同的代码时它不起作用..我我发布了我的两个代码..
应用程序.js
import React from 'react';
import {Document, Page,Text, StyleSheet, View} from '@react-pdf/renderer';
const styles = StyleSheet.create({
page: {
flexDirection: 'row',
backgroundColor: '#E4E4E4'
},
section: {
margin: 10,
padding: 10,
flexGrow: 1
}
});
function App() {
return (
<div>
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>Section #1</Text>
</View>
<View style={styles.section}>
<Text>Section #2</Text>
</View>
</Page>
</Document>
</div>
);
}
export default App;
我已经尝试过了,这工作正常..
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import DownloadButton from './DownloadButton';
const PDF = () => (
<div>
<PDFDownloadLink document={<App />} fileName="somename.pdf">
{({ blob, url, loading, error }) => (loading ? 'Loading document...' : 'Download now!')}
</PDFDownloadLink>
</div>
)
ReactDOM.render(<PDF />, document.getElementById('root'));
serviceWorker.unregister();
我想实现这一点,但得到错误..
下载Button.js
import React from 'react';
import {Document, Page,Text, StyleSheet, View} from '@react-pdf/renderer';
import {PDFDownloadLink} from '@react-pdf/renderer';
import App from './App';
class DownloadButton extends React.Component {
constructor() {
super();
}
render(){
const GeneratePdf = () => (
<div>
<PDFDownloadLink document={<App />} fileName="somename.pdf">
{({ blob, url, loading, error }) => (loading ? 'Loading document...' : 'Download now!')}
</PDFDownloadLink>
</div>
)
return(
<div>
<h4>
{<GeneratePdf />}
</h4>
</div>
);
}
}
export default DownloadButton;
解决方案
如果不是必须的就地下载,请尝试使用PDFViewer
代替PDFDownloadLink
并在新选项卡中打开它。iframe
然后设置具有全屏宽度和高度的直接父级。用户可以使用浏览器 pdf 工具包下载文件。
就像是:
<PDFViewer>
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>Section #1</Text>
</View>
<View style={styles.section}>
<Text>Section #2</Text>
</View>
</Page>
</Document>
</PDFViewer >
.iframe-parent {
height: 100vh;
}
iframe {
width: 100%;
height: 100%;
}
您可以通过 props 或 router 或 httprequest 或其他方式传递任何数据。
推荐阅读
- python-3.x - 尝试从 python 中的子包导入时出现 ModuleNotFoundError
- can-bus - 哪个 SAE J1939 PGN 编号可以删除 CAN 总线网络中的 ECU?
- python - Python:单击输入框时隐藏/删除标签
- android - LazyColumn 中每个项目的状态提升
- reactjs - CForm onSubmit 打印对象而不是字符串
- javascript - 法线贴图与减少
- java - 展开 Material BottomSheet 时如何调整 RecyclerView 的大小?
- docker - 除非我 ssh 到容器,否则 crond 不会运行
- django-rest-framework - DRF ViewSet - 处理查询参数
- node.js - 如何知道我登录 Admin-Bro 的当前用户