reactjs - react pdf 下载空白

标签 reactjs pdf react-pdf

我正在使用 React 钩子(Hook)和来自 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} 它会耗尽内存吗?

最佳答案

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

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

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

关于reactjs - react pdf 下载空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61391756/

相关文章:

javascript - 更改 Prop 时, react 表重新渲染不起作用

javascript - 添加 CSS @keyframes 动画以在 React 应用程序中进行状态更改

node.js - 如何处理来自 create-react-app 的弃用消息?

PHPExcel 创建/样式化/保存 PDF 文档

html - XSL-FO 生成的 PDF 中的图像宽度

reactjs - 如何在 IIS 上部署 React?

ruby-on-rails - 在 rails/ruby 中创建 pdf 发票

reactjs - react pdf重复故障

javascript - 无法在 React js 中加载 PDF 文件

reactjs - react-pdf中EOF后出现错误: stream. push()