简体   繁体   中英

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

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 ?

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM