0

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 Answer 1

10

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> 
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.