Creating a PDF in React JS using plain CSS and HTML

React JSJavascript LibraryFront End Technology

In this article, we will see how to create a PDF using React JS. PDFs are versatile document formats which are used for various purposes like reporting, data sharing, data storage, etc. It is really a great help if we can a PDF in React through simple CSS.

Example

First create a React app −

npx create-react-app pdfviewer

Install the react-pdf package

npm i @react-pdf/renderer

We will use this package to create a PDF inside our React frontend using DOM elements and CSS.

Insert the following piece of code in in App.js

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

// Create styles
   const styles = StyleSheet.create({
      page: {
      flexDirection: "column",
      backgroundColor: "green",
   },

   title: {
      margin: 20,
      fontSize: 25,
      textAlign: 'center',
      backgroundColor: '#E4E4E4',
      textTransform: 'uppercase',
   },

   section: {
      margin: 10,
      padding: 10,
      fontSize:25,
   },
});

// Create Document Component
const MyDocument = () => (
   <Document>
      <Page size="A4" style={styles.page}>
         <View style={styles.title}>
            <Text>Welcome to Tutorialspoint...</Text>
         </View>
         <View style={styles.section}>
            <Text>Create PDF using React</Text>
         </View>
         <View style={styles.section}>
            <Text>Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididuntut labore et dolore magna aliqua. Ut enimad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum.</Text>
         </View>
      </Page>
   </Document>
);
export default function App() {
   return (
      <PDFViewer>
         <MyDocument />
      </PDFViewer>
   );
}

Explanation

Let us understand this code in brief −

  • <Document> defines that we are going to create a PDF,

  • <Page> defines a single page of PDF, and

  • The content inside <Page> will be the content of a single page of PDF.

You can add any type of style; it is all up to you. Better design will make a better PDF.

Output

On execution, it will produce the following output −

raja
Published on 29-Sep-2021 08:49:00
Advertisements