Created
June 24, 2024 05:37
-
-
Save wp126/bfbc98ae41ad83d2b662308821e6a29b to your computer and use it in GitHub Desktop.
Download Pdf In React On page load
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// src/App.js | |
import React from 'react'; | |
import { pdf, Document, Page, Text,StyleSheet,View } from '@react-pdf/renderer'; | |
import { saveAs } from 'file-saver'; | |
function App() { | |
const styles = StyleSheet.create({ | |
page: { | |
flexDirection: 'row', | |
backgroundColor: '#E4E4E4', | |
}, | |
section: { | |
margin: 10, | |
padding: 10, | |
flexGrow: 1, | |
}, | |
}); | |
const handleDownload = async () => { | |
const doc = ( | |
<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> | |
); | |
try { | |
const blob = await pdf(doc).toBlob(); | |
saveAs(blob, 'minimalDocumdent.pdf'); | |
} catch (error) { | |
console.error('Error downloading PDF:', error); | |
} | |
}; | |
handleDownload(); | |
return ( | |
<div className="App"> | |
<h1>Download Minimal PDF Document</h1> | |
<button onClick={handleDownload}>Download PDF</button> | |
</div> | |
); | |
} | |
export default App; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment