5

I want to generate a PDF document that is generated after user click "Create PDF document" for my current React page. The document I want to generate will have the following:

  1. Some, but not all component in the current page
  2. Selectable
  3. Only download the document when clicking and nowhere else

I have spent 3 hours researching on this trivial task, but somehow all library I have looking up for only allow their pre-defined component, or not selectable, or both. I know that this task is very trivial, but how exactly I could do that?

1 Answer 1

5

The best way to do this is, having a separate component that only contains what data need to be downloaded. And you can pass all necessary data using props.

I recommend using this library React-PDF.

App.js


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

export default function App() {

  const data = {/* Pass your data here  */}
  return (
    <div className="App">
            <PDFDownloadLink document={<MyDocument data={data}/>} fileName="somename.pdf">
                {({ blob, url, loading, error }) =>
                    loading ? 'Loading document...' : 'Download now!'
                }
            </PDFDownloadLink>
    </div>
  );
}

Document.js

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

// Create styles
const styles = StyleSheet.create({
  page: {
    flexDirection: 'row',
    backgroundColor: '#E4E4E4'
  },
  section: {
    margin: 10,
    padding: 10,
    flexGrow: 1
  }
});

// Create Document Component
const MyDocument = ({ data }) => ( // 
  <Document>
    <Page size="A4" style={styles.page}>
      <View style={styles.section}>
        <Text>{data.something}</Text>
      </View>
      <View style={styles.section}>
        <Text>{data.something}</Text>
      </View>
    </Page>
  </Document>
);

In the main component, you will have a Download now! button. Your PDF will only contain data that you pass through props

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.