How to save pdf in react created using react-pdf library?

6.9k views Asked by At

I am creating a React application in which I have to generate a pdf and save that pdf when clicking a button. How can I save this pdf in my local directory ?

CreatePdf.js

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

class CreatePdf extends Component {
    constructor() {
        super();
        this.state = {
            styles: {} // all styles here
        }
    }

MyDocument = () => (
        <Document>
            <Page style={this.state.styles.body}>
                <Text style={this.state.styles.header} fixed>
                    ~ Created with react-pdf ~
                </Text>
            </Page>
        </Document>

    render() {
        return (
            <button onClick={(this.MyDocument, `${__dirname}/example.pdf`)}>Print PDF</button>
        )
    }
}
export default CreatePdf;

App.js

render() {
    return (
         <MyDocument />
    )
}

As for now, when I click on the button, nothing happens. Like in jsPDF we have .save() similarly how we can save this pdf ?

1

There are 1 answers

0
Mohammad Faisal On BEST ANSWER

you can wrap your document with PdfDownLoadLink to download the link

import { PDFDownloadLink} from '@react-pdf/renderer';


<PDFDownloadLink document={<MyDocument />} fileName={"FileName"}> 

       <button> Download </button> 

</PDFDownloadLink>