React is a popular JavaScript library for building user interfaces.
It’s possible to create PDF files from React components using the react-pdf library.
Here you will learn how to create PDF documents with React components using react-pdf.
What Is React-pdf?
React-pdf is a library that allows you to createPDF documentsfrom React components.
TheDocumentcomponent is responsible for creating a new PDF document and rendering its content.
ThePagecomponent creates a new page within the PDF document and renders its content.
Finally, theTextcomponent renders texts within the PDF document.
After creating a PDF document, you must render it in your React program.
To render the PDF document in your app, use thePDFViewercomponent, which generates the PDF document.
TheStyleSheetcomponent allows you to define custom styles for your PDF document.
To use theStylesheetcomponent, import it from the react-pdf library and define your styles for the PDF document.
For example:
In the code block above, you are adding styles to your PDF component.
You define the styles using theStylesheet.createfunction.
TheStylesheet.createfunction creates a stylesheet object containing thepageandtextstyles.
Using thestyleprop, you pass thepageandtextstyles to yourPageandTextcomponents.
This ensures that your styles apply to thePageandTextcomponents.
Adding Layouts to the PDF Document
To add layouts to your PDF document, you use theViewcomponent.
TheViewcomponent is a container component provided by the react-pdf library.
TheViewcomponent acts like an HTMLdiva fundamental HTML element.
Like so:
In this example, you use theViewcomponents to group other components.
TheImagecomponent takes asrcprop that specifies the URL of the image and astyleprop to add custom styles to your images.
In this example, you are creating a PDF document with a single page that contains an image.
TheImagecomponent displays an image with a width styling of 300 pixels and a height style of 200 pixels.
Adding Links to the PDF Document
Youll probably want to include links in your PDF document.
Links direct the user to a designated URL, which may offer supplementary information unavailable in the PDF document.
TheLinkcomponent of the react-pdf library enables you to create links within your PDF documents.
The Link component takes asrcprop to redirect users when they press the link.
They will be redirected to the URL specified in the component’ssrcprop if you define one.
To use theLinkcomponent, you first need to import it from the react-pdf library.
you might create PDF files using react-pdf, then add text, images, and links to them.