如何使用 react-pdf 下载 pdf 文件 onClick?

kar*_*017 8 reactjs

我想从 UI 生成 pdf 并下载它。一直在寻找文档,但找不到如何实现 IeonClick={this.downloadPdf}

这是模块参考:https : //github.com/diegomura/react-pdf

它说: 保存在文件中

import React from 'react';
import ReactPDF from '@react-pdf/react-pdf';

ReactPDF.render(<MyDocument />, `${__dirname}/example.pdf`);
Run Code Online (Sandbox Code Playgroud)

但这对我来说没有多大意义。

小智 15

我在他们的网站文档中找到了以下内容

import { PDFDownloadLink, Document, Page } from '@react-pdf/renderer'

const MyDoc = () => (
  <Document>
    <Page>
      // My document data
    </Page>
  </Document>
)

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


Pan*_*yay 9

嗨,它对我来说工作正常

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

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

const MyDoc = () => (
  <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>
);


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

export default App;
Run Code Online (Sandbox Code Playgroud)