如何下载带有react-pdf的onClick pdf文件?

时间:2018-08-01 00:36:53

标签: reactjs

我想从UI生成pdf并下载。一直在寻找文档,但找不到如何实现即onClick={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`);

但这对我来说意义不大。

2 个答案:

答案 0 :(得分:1)

我在下面的网站documentation中找到了

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>
)

答案 1 :(得分:0)

嗨,对我来说很好

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;