反应 pdf 下载空白

Dav*_*983 5 pdf reactjs react-pdf

我正在使用 React hooks 和 react-pdf 中的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>
    )
}
Run Code Online (Sandbox Code Playgroud)

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

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

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

当我点击下载链接时,我得到一个空白的 PDF。怎么了?

如果我不设置 wrap={false} 它会耗尽内存吗?

Gay*_*ith 1

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

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

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