首页 > 解决方案 > 使用 react-pdf/renderer 库创建 pdf 客户端

问题描述

我正在创建一个 react web 应用程序,其中必须创建一个下载按钮,该按钮在客户端创建 pdf 并下载 pdf,我正在使用 react-pdf/renderer 库来完成此任务,我已经成功实现了这个示例,我使用了这个库的 PDFDownloadLink 组件,当我将这个库直接渲染到 ReactDOM.render 中时,它工作正常,但是当我尝试在 JSX 元素中使用相同的代码时它不起作用..我我发布了我的两个代码..

应用程序.js

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

const styles = StyleSheet.create({
  page: {
    flexDirection: 'row',
    backgroundColor: '#E4E4E4'
  },
  section: {
    margin: 10,
    padding: 10,
    flexGrow: 1
  }
});

function App() {
  return (
    <div>
        <Document>
          <Page size="A4" style={styles.page}>
            <View style={styles.section}>
              <Text>Section #1</Text>
            </View>
            <View style={styles.section}>
              <Text>Section #2</Text>
            </View>
          </Page>
        </Document>
  </div>
  );
}

export default App;

我已经尝试过了,这工作正常..

index.js

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import * as serviceWorker from './serviceWorker';
import DownloadButton from './DownloadButton';

const PDF = () => (
  <div>
    <PDFDownloadLink document={<App />} fileName="somename.pdf">
      {({ blob, url, loading, error }) => (loading ? 'Loading document...' : 'Download now!')}
    </PDFDownloadLink>
  </div>
)

ReactDOM.render(<PDF />, document.getElementById('root'));
serviceWorker.unregister();

我想实现这一点,但得到错误..

下载Button.js

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

class DownloadButton extends React.Component {
  constructor() {
    super();

  }

  render(){
    const GeneratePdf = () => (
      <div>
        <PDFDownloadLink document={<App />} fileName="somename.pdf">
          {({ blob, url, loading, error }) => (loading ? 'Loading document...' : 'Download now!')}
        </PDFDownloadLink>
      </div>
    )
    return(
      <div>
        <h4>
          {<GeneratePdf />}
        </h4>
      </div>

    );
  }
}

export default DownloadButton;

标签: reactjsreact-pdf

解决方案


如果不是必须的就地下载,请尝试使用PDFViewer代替PDFDownloadLink并在新选项卡中打开它。iframe然后设置具有全屏宽度和高度的直接父级。用户可以使用浏览器 pdf 工具包下载文件。

就像是:

<PDFViewer>
    <Document>
        <Page size="A4" style={styles.page}>
            <View style={styles.section}>
                <Text>Section #1</Text>
            </View>
            <View style={styles.section}>
                <Text>Section #2</Text>
            </View>
        </Page>
    </Document>
</PDFViewer >
.iframe-parent { 
    height: 100vh; 
}
iframe {
    width: 100%;
    height: 100%;
}

您可以通过 props 或 router 或 httprequest 或其他方式传递任何数据。


推荐阅读