单击 React 中的按钮后创建 PDF 文档

Lon*_*oan 5 pdf-generation reactjs

我想生成一个 PDF 文档,该文档是在用户为我当前的 React 页面单击“创建 PDF 文档”后生成的。我想要生成的文档将具有以下内容:

  1. 当前页面中的部分(但不是全部)组件
  2. 可选
  3. 仅在单击时下载文档,其他地方不下载

我花了 3 个小时研究这个琐碎的任务,但不知何故,我查找的所有库都只允许它们的预定义组件,或者不可选,或者两者兼而有之。我知道这个任务很琐碎,但是我到底该怎么做呢?

小智 5

做到这一点的最佳方法是使用一个单独的组件,仅包含需要下载的数据。您可以使用 props 传递所有必要的数据。

我推荐使用这个库React-PDF

应用程序.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>
  );
}

Run Code Online (Sandbox Code Playgroud)

文档.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>
);
Run Code Online (Sandbox Code Playgroud)

在主要组件中,您现在可以下载按钮。您的 PDF 将仅包含您通过 props 传递的数据