Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I download a pdf file onClick with react-pdf?

Tags:

reactjs

I want to generate a pdf from the UI and download it. Been looking to the documentation but couldn't find how to implement I.e. onClick={this.downloadPdf}

here's the module reference: https://github.com/diegomura/react-pdf

It says: Save in a file

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

ReactPDF.render(<MyDocument />, `${__dirname}/example.pdf`);

But this doesn't make much sense to me.

like image 250
karolis2017 Avatar asked Aug 01 '18 00:08

karolis2017


2 Answers

I have found below in their site 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>
)
like image 75
gujaru Avatar answered Nov 19 '22 19:11

gujaru


hi its working fine for me

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;
like image 38
Pankaj Upadhyay Avatar answered Nov 19 '22 17:11

Pankaj Upadhyay