【问题标题】:React pdf downloads blankReact pdf下载空白
【发布时间】:2020-08-07 01:06:03
【问题描述】:

我正在使用 React 钩子和来自 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>
    )
}

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

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

然后我在 JSX 的 div 中添加了 {stuff}。

当我单击下载链接时,我得到一个空白 PDF。发生了什么?

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

【问题讨论】:

    标签: reactjs pdf react-pdf


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 2015-04-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-07
      • 1970-01-01
      • 1970-01-01
      • 2016-03-29
      相关资源
      最近更新 更多