Maison  >  Article  >  interface Web  >  Comment créer des PDF à l'aide de React JS

Comment créer des PDF à l'aide de React JS

Barbara Streisand
Barbara Streisandoriginal
2024-10-18 14:59:05850parcourir

Introduction

Parfois, vous devez enregistrer les tableaux ou les données de votre application au format PDF pour un partage facile. Avec React PDF Renderer, vous pouvez facilement transformer vos composants React en PDF de haute qualité. Dans ce blog, nous apprendrons comment simplifier la transformation de votre contenu Web en PDF partageables.

React PDF Renderer possède son propre ensemble de composants, qui sont un peu différents des composants React classiques ou des balises HTML. Mais sa fonctionnalité est facile à comprendre. Une fois que vous aurez appris les bases, vous serez en mesure d'utiliser efficacement React PDF Renderer pour créer des PDF dans vos applications React. Avant d'entrer dans le code, nous examinerons d'abord les principaux composants fournis par React PDF Renderer et verrons comment ils fonctionnent.

Conditions préalables

  1. Connaissance de base de React
  2. Node.js et npm installés sur votre machine
  3. Familiarité avec CSS
  4. Un projet React existant mis en place (nous en parlerons)

Avec ces bases, vous êtes prêt à démarrer le processus de conversion de vos composants React en PDF.

Composants du moteur de rendu React PDF

React PDF Renderer utilise divers composants pour vous aider à convertir les composants React en PDF. Voici les composants clés et leurs utilisations :

  • Document : L'élément racine pour créer un document PDF.
  • Page : représente une seule page dans le PDF.
  • View : Un élément conteneur similaire à un div en HTML.
  • Texte : utilisé pour afficher le texte dans le PDF.
  • Image : Vous permet d'inclure des images dans votre PDF.
  • Lien : Active les liens cliquables dans le PDF.
  1. Afficher le composant :

    • Utilisation : agit comme un conteneur pour d'autres composants, similaire à dc6dce4a544fdca2df29d5ac0ea9906b en HTML.
    • Format de style : prend en charge les styles tels que la largeur, la hauteur, la marge, le remplissage, la couleur d'arrière-plan, la bordure, etc.
    <View style={{ width: 100, height: 50, backgroundColor: 'blue' }} >
    /* pdf content */
    </View>
    
  2. Composant texte :

    • Utilisation : restitue le contenu du texte dans le document PDF.
    • Format de style : prend en charge la taille de la police, la famille de polices, l'épaisseur de la police, l'alignement du texte, la couleur et d'autres styles liés au texte.
    <Text style={{ fontSize: 14, fontWeight: 'bold', color: 'black' }}>
    Hello, World!
    </Text>
    
  3. Composant d'image :

    • Utilisation : Intégrez des images dans le document PDF.
    • Format de style : prend en charge des propriétés telles que la largeur, la hauteur et l'URL source de l'image.
    <Image src="example.jpg" style={{ width: 200, height: 100 }} />
    
  4. Composant de page :

    • Utilisation : définit des pages individuelles dans le document PDF.
    • Format de style : prend en charge des propriétés telles que la taille, l'orientation et les marges pour chaque page.
    <Page size="A4" style={{ margin: 10 }}>Page Content</Page>
    
  5. Composant de lien :

    • Utiliser : Crée des hyperliens dans le document PDF.
    • Format de style : prend en charge la définition de l'URL et les options de style pour le lien hypertexte.
    <Link src="https://example.com" style={{ color: 'blue' }}>
      Click here
    </Link>
    
  6. Composant Document :

    • Utilisation : Représente l'intégralité du document PDF.
    • Format de style : prend en charge les paramètres globaux du document tels que la taille de la page, les marges et les métadonnées.
    <Document title="Example Document">
    <Page>
      <Text>
          Content
      </Text>
    </Page>
    </Document>
    

Ce sont les composants de base utilisés lorsque vous travaillez avec React PDF. Vous pouvez voir une liste complète des composants avec les accessoires valides disponibles ici.

Configuration de l'environnement

Vous pouvez commencer à créer vos PDF dans votre application existante, ou vous pouvez utiliser un REPL en ligne spécifiquement pour React PDF. L'avantage d'un React PDF REPL en ligne est que nous pouvons visualiser instantanément l'aperçu de notre code. Sans ce système de prévisualisation, nous aurions besoin de télécharger le PDF à chaque fois pour le visualiser.

Nous utiliserons donc le REPL en ligne pour React PDF car il nous permet de prévisualiser instantanément nos modifications de code. Cet aperçu est idéal lors de la création d'un PDF, car il nous fait gagner du temps et nous aide à détecter les erreurs plus tôt. Cependant, j'expliquerai également comment vous pouvez configurer React PDF dans votre application React.

Créons une nouvelle application React, installons React PDF Renderer et écrivons notre première ligne de code avec.

Ouvrez votre terminal et exécutez la commande suivante pour créer une nouvelle application React à l'aide de Create React App

npx create-react-app my-react-pdf-app

Cette commande créera un nouveau répertoire nommé my-react-pdf-app avec une configuration de base de React.

cd my-react-pdf-app

Utilisez npm pour installer la bibliothèque React PDF Renderer.

npm install @react-pdf/renderer

Ouvrez le projet nouvellement créé (my-react-pdf-app) dans votre éditeur de code préféré (comme VSCode). Créez un nouveau fichier nommé MyDocument.js dans le répertoire src.

// src/MyDocument.js

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

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

// Create Document Component
const MyDocument = () => (
  5e4f0452c956abb82e6662046a0f6630
    f62a09f3ac49e1b121eab0a662e707ab
      65c25a3ac84fa161f59dba223913d55d
        7afbc23223af17d69e2ad2a4e42c6248Section #1b735fb8965edb39ac28662131d16c063
      3d260b73c372472a96940693fb62cbcc
      65c25a3ac84fa161f59dba223913d55d
        7afbc23223af17d69e2ad2a4e42c6248Section #2b735fb8965edb39ac28662131d16c063
      3d260b73c372472a96940693fb62cbcc
    768cdee1b4b725a4a4a773fe2d988b48
  e4a958d5d76049640eeb8862309d22ea
);

export default MyDocument;

Ouvrez App.js et modifiez-le pour afficher le document PDF.

// src/App.js

import React from 'react';
import { PDFDownloadLink } from '@react-pdf/renderer';
import MyDocument from './MyDocument';

const App = () => (
  d7ae34ce73578a20fe774d5bff7fdec1
    52a0d453c6b753de18addead7faa5270
      2a5e2cb62ffa546b17d950c2d80a5565} fileName="mypdf.pdf">
        {({ blob, url, loading, error }) =>
          loading ? 'Loading document...' : 'Download PDF now!'
        }
      a2e48c1b8615792ef118bf94ebf72b0f
    ab946e7546ab66a280dd9c9f9310ecd5
  16b28748ea4df4d9c2150843fecfba68
);

export default App;

Ouvrez votre terminal, assurez-vous que vous êtes dans le répertoire du projet et démarrez le serveur de développement.

npm start

Your default browser should automatically open and navigate to http://localhost:3000, where you will see a link to download the PDF.

How to Create PDFs using React JS

But in this blog, we will use an Online Code REPL so that we can see the output instantly. Then, we can use the same code in our React app to download it. Both methods will give the same result.

Code PDF

So, we are going to code this PDF design. With this design, we will understand how all the components work. After that, you can code any PDF design.

How to Create PDFs using React JS

So, till now, we understand that there are three major components for React PDF:

  • Document
  • Page
  • View

This PDF design is also divided into these three main components.

How to Create PDFs using React JS

So, from the above diagram, I hope you understand what we need to build first. First, we will create a document using the 5e4f0452c956abb82e6662046a0f6630 component. Then, we will declare a 9bf8075cc227fc55eb2ec8dec5c506d4, and after that, we will declare a 548e7793df275d156d270cdda504ba19 and start defining our components there.

Steps:

Basic Setup
Start with importing basic things and components we need to use for React PDF.

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

Document Styling
Now we will style our document. Here, we will set how our entire document looks. We will use StyleSheet.create to define the styles for our PDF components. This is similar to CSS but written in JavaScript objects:

const styles = StyleSheet.create({
  page: {
    padding: 20,
    backgroundColor: '#ffffff'
  },
  section: {
    marginBottom: 20
  }
});
// we will add more style later on.

Here, we will use the page and section styles in our components like this.

164ad81a262e166f89474676f68481d7

Define Data
Define the data you want to display in the PDF document. This data can be dynamic and fetched from an API or a database:

const data = [
  {
    title: 'Attack on Titan',
    studio: 'Wit Studio',
    genre: 'Action, Dark Fantasy',
    releaseDate: '04-07-2013',
    status: 'Completed',
    rating: '9.0',
    cost: '$120'
  }
];

Create Document Component
Define the MyDocument component which will structure the PDF document. The name can be anything. It is our React component.

const MyDocument = () => {
 return (
   // Our pdf code will be here
     );
};
export default MyDocument;

The component returns JSX that describes the structure of the PDF document. So, in the return statement, we will start by using our first React PDF component, which is 7d26fa5b48246651078c945a5dd27298.

const MyDocument = () => {
 return (
     5e4f0452c956abb82e6662046a0f6630
       /* Here we will steup our page */
     e4a958d5d76049640eeb8862309d22ea
     );
};
export default MyDocument;

This creates a Black PDF Document.

How to Create PDFs using React JS

Create PDF Pages
Now, let's start by creating pages for our PDF. Use the 9bf8075cc227fc55eb2ec8dec5c506d4 component to define pages. The number of 9bf8075cc227fc55eb2ec8dec5c506d4 components will determine the number of pages. For example, if you use two 9bf8075cc227fc55eb2ec8dec5c506d4 tags, your PDF will have two pages. If you have too much data for a single page, React PDF will automatically create additional pages as needed.

The 9bf8075cc227fc55eb2ec8dec5c506d4 component has several props, such as size, which defines the page size like A4, A2, A3, etc., along with many other props. You can see all page props here.

How to Create PDFs using React JS

// Create Document Component
const MyDocument = () => {
  return (
    5e4f0452c956abb82e6662046a0f6630
      f62a09f3ac49e1b121eab0a662e707ab
        548e7793df275d156d270cdda504ba19 
          7afbc23223af17d69e2ad2a4e42c6248Hellob735fb8965edb39ac28662131d16c063
        3d260b73c372472a96940693fb62cbcc
      768cdee1b4b725a4a4a773fe2d988b48
    e4a958d5d76049640eeb8862309d22ea
  );
};
export default MyDocument;

Here, we use the 9bf8075cc227fc55eb2ec8dec5c506d4 component and add a size prop, giving it a value. We also use the style defined in our style object. Inside the 9bf8075cc227fc55eb2ec8dec5c506d4 component, we are using the 548e7793df275d156d270cdda504ba19 component, and within that, we are using the 7afbc23223af17d69e2ad2a4e42c6248 component to display the text "Hello." The output will look like this:

How to Create PDFs using React JS

So, the View component works just like a div. For example, if you want a big box in your PDF divided into specific columns, and you want to give each column a different color, you just need a few View components and some styling. If you need to add text, use the Text component. To add an image, use the Image component. Check the code and output below.

// Create styles
const styles = StyleSheet.create({
  page: {
    padding: 20,
    backgroundColor: '#ffffff'
  },
  section: {
    marginBottom: 20
  },
  bigBox: {
    flexDirection: 'row',
    marginBottom: 20,
    borderWidth: 1,
    borderColor: '#000',
  },
  column: {
    flex: 1,
    padding: 10,
    borderWidth: 1,
    borderColor: '#000',
  },
  column1: {
    backgroundColor: '#ffcccc',
  },
  column2: {
    backgroundColor: '#ccffcc',
  },
  column3: {
    backgroundColor: '#ccccff',
  },
  text: {
    fontSize: 12,
  },
  image: {
    width: "auto",
    height: 100,
  },
  canvas: {
    width: '100%',
    height: 100,
    borderWidth: 1,
    borderColor: '#000',
    backgroundColor: '#e0e0e0',
  }
});

// Create Document Component
const MyDocument = () => {
  return (
      5e4f0452c956abb82e6662046a0f6630
    f62a09f3ac49e1b121eab0a662e707ab
      e083f898c6a88be4e07aab1713b82b7e
        9df84018ceed6bd882576384b887180b
          39954ff4c9e4db30e0ee1fc3bb4fc2adThis is a text columnb735fb8965edb39ac28662131d16c063
        3d260b73c372472a96940693fb62cbcc
        ff1825fdb126314f18619f60b9c1b2de
          b2470f12f33ae95c3e2d32a5d643f772
        3d260b73c372472a96940693fb62cbcc
        19705b263d431bf38aed3ede2eb87325
          a99003f66f50a5e4cc78e3fd02cbf161
            39954ff4c9e4db30e0ee1fc3bb4fc2adCanvas section (Placeholder)b735fb8965edb39ac28662131d16c063
          3d260b73c372472a96940693fb62cbcc
        3d260b73c372472a96940693fb62cbcc
      3d260b73c372472a96940693fb62cbcc
    768cdee1b4b725a4a4a773fe2d988b48
  e4a958d5d76049640eeb8862309d22ea
  );
};

export default MyDocument;

How to Create PDFs using React JS

Explanation

  • styles.bigBox: This style defines the main container that holds the three columns.
  • styles.column: This style defines the base style for each column, including padding and borders.
  • styles.column1, styles.column2, styles.column3: These styles define the background colors for each column.
  • styles.text: This style is used for the text inside the first column.
  • styles.image: This style is used for the image inside the second column.
  • styles.canvas: This style defines the placeholder canvas section inside the third column.

Here, each column is given a different background color for visual separation. The first column contains text, the second contains an image, and the third contains a placeholder for a canvas section.

So, for this, we just used the View, Text, and Image components. I hope you now understand that to create any component, we only need a few components to create a PDF in React. Now, let's return to our main design. We will use the same components and add some styling like flex, border styling, font styling, etc.

How to Create PDFs using React JS

Let's create the header first. We need to use a View component as the header, apply some styles using flex, and add Image and Text components to it.

// src/MyDocument.js
import React from 'react';
import { Page, Text, View, Document, StyleSheet, Image } from '@react-pdf/renderer';

// Create styles
const styles = StyleSheet.create({
  page: {
    padding: 20,
    backgroundColor: '#ffffff'
  },
  section: {
    marginBottom: 20
  },
  headerContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginBottom: 20
  },
  headerText: {
    fontSize: 20,
    fontWeight: 'bold'
  },
  image: {
    width: 50,
    height: 50
  },
  date: {
    fontSize: 12,
    textAlign: 'right'
  },
});
// Create Document Component
const MyDocument = () => {
  return (
        5e4f0452c956abb82e6662046a0f6630
      f62a09f3ac49e1b121eab0a662e707ab
        65c25a3ac84fa161f59dba223913d55d
          d81020391e9a1e9e7184a59ac3fd2ec9
            56eaf10c7301651cea8f447a8c5a9b2f
            4c99eff61a1244fa7b73bb6939161067Anime Reportb735fb8965edb39ac28662131d16c063
            26b82f871a2a216f2d655d904af97a08{new Date().toLocaleDateString()}b735fb8965edb39ac28662131d16c063
            3d260b73c372472a96940693fb62cbcc
          3d260b73c372472a96940693fb62cbcc
      768cdee1b4b725a4a4a773fe2d988b48
    e4a958d5d76049640eeb8862309d22ea
  );
};

export default MyDocument;

How to Create PDFs using React JS

You see, it's easy to grasp.

Let's code the table. To create tables using React PDF Renderer, we just need to use flex styling and the View and Text components. Each View component will contain one Text component, but you can add more Text components if needed.

The Main Structure

This code will create a table in a PDF document.

f3e30c3a6c14cdf9d1097ae9176a520e
  {/* Table Header */}
  2a771865ce4bcf8501c0e7132cefe043
    {/* Each Column Header */}
    3b248e8febf36e71ef673d6bd1e9793f
      723631ac8b1f909a8cf0faa818558df2Titleb735fb8965edb39ac28662131d16c063
    3d260b73c372472a96940693fb62cbcc
    {/* More column headers... */}
  3d260b73c372472a96940693fb62cbcc
  {/* Table Rows */}
  {data.map((item, index) => (
    8940b7edfa38482a1b18f3b1d2b332b2
      {/* Each Column in a Row */}
      3cf60c0359dc6945f5fdf28a20f40b67
        e61307a8a3f08727a3101e2a080aeae4{item.title}b735fb8965edb39ac28662131d16c063
      3d260b73c372472a96940693fb62cbcc
      {/* More columns... */}
    3d260b73c372472a96940693fb62cbcc
  ))}
3d260b73c372472a96940693fb62cbcc
  1. Table Container

    <View style={styles.table}>
    

    This View acts as the main container for the entire table. The styles.table style will define how the table is displayed, like borders, padding, etc.

  2. Table Header Row

    <View style={styles.tableRow}>
    

    This View represents a row in the table. The styles.tableRow style will apply to both the header row and each data row.

  3. Column Headers

    <View style={styles.tableColHeader}>
    <Text style={styles.tableCellHeader}>Title</Text>
    </View>
    

    Each View inside the header row is a column header. The styles.tableColHeader style will define how the header cells look, such as their background color, borders, and text alignment. The Text component inside it contains the column's title and uses the styles.tableCellHeader style for text styling. Repeat this for each column header (e.g., Title, Studio, Genre, Release Date, Status, Rating, Cost).

  4. Data Rows

    {data.map((item, index) => (
    <View style={styles.tableRow} key={index}>
     {/* Columns for each row */}
    </View>
    ))}
    

    Here, we use the map function to loop over an array called data. For each item in the array, it creates a new row in the table. The key attribute helps React manage the list of items efficiently.

  5. Columns in Data Rows

    <View style={styles.tableCol}>
    <Text style={styles.tableCell}>{item.title}</Text>
    </View>
    

    Each View inside the data row is a column. The styles.tableCol style will define the appearance of the cells in the data rows, and the Text component inside displays the actual data. The styles.tableCell style is applied to the text for consistent styling. Repeat this for each column in the data row (e.g., item.title, item.studio, item.genre, item.releaseDate, item.status, item.rating, item.cost).

  6. Table Code

    // React PDF Renderer Component
    import React from 'react';
    import { Page, Text, View, Document, StyleSheet } from '@react-pdf/renderer';
    // Create styles
    const styles = StyleSheet.create({
    // after date styling....
    table: {
      display: "table",
      width: "auto",
      borderStyle: "solid",
      borderWidth: 1,
      borderColor: '#bfbfbf'
    },
    tableRow: {
      flexDirection: "row"
    },
    tableColHeader: {
      width: "15%",
      borderStyle: "solid",
      borderWidth: 1,
      borderColor: '#bfbfbf',
      backgroundColor: '#f0f0f0'
    },
    tableCol: {
      width: "15%",
      borderStyle: "solid",
      borderWidth: 1,
      borderColor: '#bfbfbf'
    },
    tableCellHeader: {
      margin: 5,
      fontSize: 10,
      fontWeight: "bold"
    },
    tableCell: {
      margin: 5,
      fontSize: 10
    },
    footerContainer: {
      flexDirection: 'row',
      justifyContent: 'space-between',
      alignItems: 'center',
      marginTop: 20
    },
    footerText: {
      fontSize: 12
    },
    totalCost: {
      fontSize: 12,
      fontWeight: 'bold'
    }
    });
    const data = [
    {
      title: 'Attack on Titan',
      studio: 'Wit Studio',
      genre: 'Action, Dark Fantasy',
      releaseDate: '04-07-2013',
      status: 'Completed',
      rating: '9.0',
      cost: '$120'
    },
    // You can add more or fetch data from an API or database
    ];
    // Create Document Component
    const MyDocument = () => (
    
    
       /* After header code */
      <View style={styles.table}>
        <View style={styles.tableRow}>
          
            Title
          
          
            Studio
          
          
            Genre
          
          
            Release Date
          
          
            Status
          
          
            Rating
          
          
            Cost
          
        
        {data.map((item, index) => (
          
            
              {item.title}
            
            
              {item.studio}
            
            
              {item.genre}
            
            
              {item.releaseDate}
            
            
              {item.status}
            
            
              {item.rating}
            
            
              {item.cost}
            
          
        ))}
      
    
    
    );
    export default MyDocument;
    

    Here, we've created a simple table with headers and data rows. Each item in the data array becomes a row in the table, and each property of the item becomes a cell in that row. The styling makes sure the table looks neat and professional in the PDF document.

How to Create PDFs using React JS

Now, at the end, we can code a footer. The code below creates a footer with an image and a text displaying the total cost.

// style code after table styles...

  footerContainer: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    marginTop: 20
  },
  footerText: {
    fontSize: 12
  },
  totalCost: {
    fontSize: 12,
    fontWeight: 'bold'
  }

//... After table code add footer

1973e766c157f8d31ba188d30374dca8
  56eaf10c7301651cea8f447a8c5a9b2f
  c3fcc784b557b2f1c4fe82e26015222bTotal Cost: ${calculateTotalCost()}b735fb8965edb39ac28662131d16c063
3d260b73c372472a96940693fb62cbcc

This View acts as the main container for the footer. The styles.footerContainer style defines how the footer is displayed, including its layout, padding, margin, and alignment. The Image component displays an image, while the Text component shows the total cost.

Conclusion

In this blog, we covered how to use React PDF Renderer to convert React components into high-quality PDFs. We covered the key components, including Document, Page, View, Text, Image, and Link, and explained their uses and styling. We covered, creating a basic PDF document, adding pages, styling, and building complex structures like tables and footers. By following this, you can easily transform your web content into shareable PDFs using React.

Merci d'avoir lu ce blog. Si vous en avez appris quelque chose, aimez-le et partagez-le avec vos amis et votre communauté. J'écris des blogs et partage du contenu sur JavaScript, TypeScript, Open Source et d'autres sujets liés au développement Web. N'hésitez pas à me suivre sur mes réseaux sociaux. Je te verrai dans le prochain. Merci :)

  • Twitter
  • LinkedIn
  • GitHub

Documents officiels du moteur de rendu PDF React

Réagir au moteur de rendu PDF NPM

Code complet

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn