【发布时间】:2021-09-06 13:54:11
【问题描述】:
我想为我当前的 React 页面生成用户单击“创建 PDF 文档”后生成的 PDF 文档。我要生成的文档将具有以下内容:
- 当前页面中的一些,但不是所有组件
- 可选
- 仅在单击时下载文档,在其他地方不下载
我花了 3 个小时研究这个微不足道的任务,但不知何故,我查找的所有库都只允许它们的预定义组件,或者不可选择,或两者兼而有之。我知道这项任务非常琐碎,但我究竟该怎么做呢?
【问题讨论】:
我想为我当前的 React 页面生成用户单击“创建 PDF 文档”后生成的 PDF 文档。我要生成的文档将具有以下内容:
我花了 3 个小时研究这个微不足道的任务,但不知何故,我查找的所有库都只允许它们的预定义组件,或者不可选择,或两者兼而有之。我知道这项任务非常琐碎,但我究竟该怎么做呢?
【问题讨论】:
最好的方法是使用一个单独的组件,只包含需要下载的数据。你可以使用 props 传递所有必要的数据。
我推荐使用这个库React-PDF。
App.js
import { PDFDownloadLink } from '@react-pdf/renderer';
import Document from './Document.js'
export default function App() {
const data = {/* Pass your data here */}
return (
<div className="App">
<PDFDownloadLink document={<MyDocument data={data}/>} fileName="somename.pdf">
{({ blob, url, loading, error }) =>
loading ? 'Loading document...' : 'Download now!'
}
</PDFDownloadLink>
</div>
);
}
Document.js
import React from 'react';
import { Document, Page, Text, View, StyleSheet } from '@react-pdf/renderer';
// Create styles
const styles = StyleSheet.create({
page: {
flexDirection: 'row',
backgroundColor: '#E4E4E4'
},
section: {
margin: 10,
padding: 10,
flexGrow: 1
}
});
// Create Document Component
const MyDocument = ({ data }) => ( //
<Document>
<Page size="A4" style={styles.page}>
<View style={styles.section}>
<Text>{data.something}</Text>
</View>
<View style={styles.section}>
<Text>{data.something}</Text>
</View>
</Page>
</Document>
);
在主组件中,您将有一个 立即下载! 按钮。您的 PDF 将仅包含您通过 props 传递的数据
【讨论】: