React pdf 下载空白

React pdf downloads blank

我正在使用 react-pdf

的 React hooks 和 react-pdf

我尝试了 3 种不同的 React pdf 转换器,这是迄今为止效果最好的一种。它仍然不能很好地工作 - 我看不出如何使它既不会 运行 内存不足也不会生成空白 pdf。

我有一个生成 pdf 的组件:

import React from 'react';
import { Page, Text, View, Document, StyleSheet, Font } from '@react-pdf/renderer';

Font.register({
    family: 'Roboto',
    src: 'https://fonts.googleapis.com/css?family=Roboto+Mono:100i,300,300i,400,400i,500,500i,700,700i&display=swap'
  });

// Create styles
const styles = StyleSheet.create({
  page: { 
    backgroundColor: '#F5F8FA',
    display: 'flex',
    // flexDirection: 'column',
    // alignItems: 'flex-start',
    marginTop: 40,
    marginLeft: 20,
    marginRight: 20,
    width: 555
  },
  section: {
    margin: 50,
    padding: 50,
  },
  reportHeader: {
    marginLeft: 0,
    fontStyle: 'normal',
    fontWeight: 'bold',
    fontSize: 24,
    lineHeight: 43,
    color: '#BF802F',
  },
  reportIntro: {
    width: 555,
    height: 132,
    paddingLeft: 0,
    paddingTop: 10,
    paddingBottom: 30,
    fontStyle: 'normal',
    fontWeight: 'normal',
    fontSize: 16,
    lineHeight: 22,
    color: '#0C3957',
  }
});

// Create Document Component
export const ReportPDF = ({ name, adviser }) => {

    return (
  <Document > 
    <Page style={styles.page} wrap={false}>
      <View style={{ textAlign: 'flex-start', marginBottom: 20 }}>
        <Text style={styles.reportHeader}>Your goals report</Text>
      </View>
    </Page>
  </Document>
    )
}

我还有另一个组件,它有一个用于下载 pdf 文件的按钮。我发现有人声称 useMemo 可以帮助解决这种情况,但我也不能让它以这种方式工作:

const stuff = useMemo(
        () => (
          <PDFDownloadLink document={<ReportPDF />} fileName="somename.pdf">
            {({ blob, url, loading, error }) => (loading ? 'Loading document...' : 'Download now!')}
          </PDFDownloadLink>
        ), [])

然后我在 JSX 的 div 中有 {stuff}。

当我点击下载 link 时,我得到一个空白的 PDF。发生了什么事?

如果我不设置 wrap={false} 它运行内存不足?

发生这种情况的原因之一是,pdf 在获取数据之前呈现。因此,您可以在呈现 PDFDownloadLink 之前添加条件以防止出现这种情况。

  !loadingReportData && <PDFDownloadLink document={<ReportPDF />} fileName="somename.pdf">
    {({ blob, url, loading, error }) => (loading ? 'Loading document...' : 'Download now!')}
  </PDFDownloadLink>

(这里的loadingReportData是状态,你在取报表数据前设置为true,取报表数据完成后设置为false)