alt descriptionalt description
08/13/21
Mark Mooney
React-PDF/Renderer: Build, display, save, or print a dynamic PDF quickly
Main Image
What is React-PDF/renderer?

After countless hours (days? weeks?...months?), you've finished development. The code is stable, the styling is perfect, and everything is deployed and ready. A user just filled out a form in the application. They need a way to share the completed form. Maybe it has to be printed or added as an attachment to an email. You could do the tedious and repetitive work yourself; gathering the data from each input, adding it to a document, generating a pdf, and then sending it to the user. But there has to be a better, faster, cheaper way to manage these processes.

React-pdf/renderer allows custom pdf builds using a series of components similar to React's. These components come with default props and can be further customized as needed. The latest version of the library also includes a hook for fine-tuning when and how your PDF is generated.
import React from 'react'; import { Page, Text, View, Document, StyleSheet, Image, Canvas } from '@react-pdf/renderer'; import Header from './Header/header.js'; import Footer from './Footer/footer.js'; import SampleTable from './Table/table.js'; import sampleImage from './images/desertSample.jpg'; // Create styles const styles = StyleSheet.create({ document: { display: 'flex', width: '100%', height: '100%' }, page: { flexDirection: 'row', backgroundColor: '#fff', }, pageWrapper: { padding: 25, position: 'absolute', justifyContent: 'space-around' } }); const PageWrapper = (props) => { return ( <Page size="Letter" style={styles.pageWrapper}> <Header /> {props.children} <Footer /> </Page> ); }; const TestPDF = () => ( <Document> <PageWrapper> <View style={{ flexDirection: 'column' }}> <View style={{ flexDirection: 'row' }}> <View style={{ width: '50%', padding: 5 }}> <Text style={{ fontSize: 9 }}> It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using 'Content here, content here', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for 'lorem ipsum' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like). </Text> </View> <View style={{ width: '50%', padding: 5 }}> <Image src={sampleImage} /> </View> </View> <View style={{ flexDirection: 'row', padding: 20 }}> <View style={{ width: '50%', paddingTop: 20, paddingRight: 10 }}> <Canvas style={{ availableWidth: 100, availableHeight: 100, backgroundColor: 'black' }} paint={painter => painter .moveTo(3, 87) .lineTo(87, 3) .lineTo(50, 125) .lineTo(125, 50) .lineTo(100, 125) .fill('green') .moveTo(75, 75) .lineTo(62, 100) .lineTo(100, 62) .lineTo(112, 87) .fill('red') .moveTo(62, 112) .lineTo(75, 112) .lineTo(125, 100) .lineTo(62, 130) .fill('blue') } /> </View> <View style={{ width: '50%', padding: 5 }}> <SampleTable /> </View> </View> <View style={{ flexDirection: 'row' }}> <View style={{ width: '50%', padding: 5 }}> <Text style={{ fontSize: 9 }}> But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure? </Text> </View> </View> </View> </PageWrapper> </Document> ); export default TestPDF;
The snippet above shows the main layout for a basic single page PDF. It includes a StyleSheet, multiple default components, and a custom table component.

React-pdf/renderer’s default components build from the top down starting with a <Document />. This serves as a container for any child components. The document is mainly composed of <Page />, <View />, <Text />, and <Image /> components, but can include <Note />, <Link />, and <Canvas /> elements as well. The entire document can then be wrapped in either <PDFViewer />, <PDFDownloadLink />, or <BlobProvider /> depending on the preferred method of delivery.

Styling can be done in line with the style prop or via an external StyleSheet.create(), or with a combination of the two. This setup paired with a FlexBox layout allows for extensive customization. As expected from a react library, conditional styling is also available.
const styles = StyleSheet.create({ tableWrapper: { flex: 1, display: 'flex', flexWrap: 'wrap', flexDirection: 'row', paddingBottom: 10, marginBottom: 25, fontSize: 11, borderTop: '3 solid #494949', }, columnHeader: { display: 'flex', flexWrap: 'wrap', borderBottom: '1 solid #494949', textAlign: 'left', }, rowVal: { color: 'black', whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis', } });
Styling with StyleSheet.create()
style= {{ ...styles.rowVal, width: item?.width, fontSize: 8, borderBottom: '1 solid #494949', textAlign: textAlign, padding: 6, paddingVertical: 3, paddingRight: 15, borderRight: item?.showBorderRight ? '1 solid #494949' : 'none', borderLeft: item?.showBorderLeft ? '1 solid #494949' : 'none' }}
In-line styling/StyleSheet combo

What can you do with it?

With an easy setup and a familiar structure, React-PDF/renderer can quickly generate client side documents for display in the browser or for download, all depending on which component type you use to wrap the document. Using the React-pdf quick-start guide as a starting point, the code snippets shown above and linked in this repo, I created a document with a header and footer, a table with some static content, one image (.jpg), a poor attempt at modern art (canvas component) and a couple of text blurbs.

The footer includes dynamic page numbers and the current date (using Moment). Images can be rendered locally or with a url, and the <Image /> component supports PNG, JPG, and SVG formats. Notice that even with the <PDFViewer /> component, download and print options are available for the user.

What did we learn?

React-PDF/renderer is a powerful library for displaying dynamic content in a convenient format. It uses a set of default components and any custom ones you create as well. Like any React build, your components can be reused as often as needed. The library is extremely flexible, regularly updated, and generates a final product familiar to most users. Once you decide how to lay out your components and wire in your database, your custom PDF is ready to go!


BPA Logo
Get in Touch
+1 770.744.4027info@barrelproofapps.com2451 Cumberland Parkway SESuite 3949Atlanta, GA 30339