react-pdf

repository·master·Indexed 12 days ago

https://github.com/diegomura/react-pdf

A React renderer for creating PDF files on both the browser and the server, allowing developers to use React components and styles to define PDF layouts. The ecosystem includes @react-pdf/root (v2.0.0), @react-pdf/font for font registration and loading (TTF, WOFF, WOFF2), @react-pdf/fns for functional programming utilities, and @react-pdf/image for image parsing and resolution.

Tokens
22.7K
Snippets
82
Records
111
Agent score
94%

What's inside react-pdf

  1. Overview of @react-pdf/pdfkit features

    master

    The @react-pdf/pdfkit library is a PDF generation tool that supports creating complex, multi-page documents. Key capabilities include:

    • Vector Graphics: Provides an HTML5 canvas-like API with path operations, SVG path parsing, transformations, and linear/radial gradients.
    • Text Handling: Supports line wrapping, text alignments, and bulleted lists.
    • Font Embedding: Supports multiple formats including TrueType (.ttf), OpenType (.otf), WOFF, WOFF2, TrueType Collections (.ttc), and Datafork TrueType (.dfont). It also supports font subsetting.
    • Image Embedding: Supports JPEG and PNG files (including indexed PNGs and PNGs with transparency).
    • Annotations: Supports links, notes, highlights, underlines, and more.
  2. Explore React-pdf feature examples

    master

    The Vite examples package contains a catalog of implementations demonstrating various react-pdf capabilities. Key features demonstrated include:

    • Typography & Text: Ellipsis truncation, Emoji (Twemoji) rendering, Font family fallbacks, Font weights, Multiline text styling, Soft hyphens, and complex World Scripts (Bengali, Tamil, Thai, Arabic, etc.).
    • Layout & Responsiveness: Media queries for responsive layouts, Page wrapping with headers/page numbers, and minPresenceAhead for controlling page breaks.
    • Images & Graphics: Image deduplication, JPEG EXIF orientation handling, Object Fit modes (contain, cover, none), Responsive images via srcSet, and SVG support (paths, gradients, patterns, and transforms).
    • Advanced Components: Interactive Forms (inputs, checkboxes, selects), Internal document navigation (Go To/anchors), Math (LaTeX) via @react-pdf/math, and ImageBackground with overlaid content.
  3. Parse CSS transform strings

    master

    The engine parses CSS transform strings into a structured array of operation objects.

    Supported functions:

    • translate(x, y) / translateX(x) / translateY(y)
    • rotate(angle)
    • scale(x, y) / scaleX(x) / scaleY(y)
    • skew(x, y) / skewX(x) / skewY(y)
    • matrix(a, b, c, d, e, f)

    Example:

    // Input
    { transform: 'translate(10, 20) rotate(45) scale(2)' }
    
    // Output
    {
      transform: [
        { operation: 'translate', value: [10, 20] },
        { operation: 'rotate', value: [45] },
        { operation: 'scale', value: [2, 2] },
      ]
    }
  4. Understand the @react-pdf/stylesheet types

    master

    The @react-pdf/stylesheet package uses several key types to manage CSS-like styling for PDF generation.

    • Container: Defines the context for style resolution, including dimensions and unit conversion settings.
    • Style: The input type for your style objects. It supports a wide range of CSS-like properties including Flexbox, Spacing, Borders, Layout, Colors, Text, and SVG properties. It also supports media queries using the @media prefix.
    • SafeStyle: The output type after the stylesheet engine has processed the input. It contains normalized values where all shorthand properties are expanded, units are converted to points (numbers), colors are normalized, and transforms are parsed into structured arrays.
    • Transform: A structured representation of CSS transforms.
    • FontWeight: A union of numeric weights and named CSS font weight strings.
  5. Expand CSS shorthands

    master

    The engine expands shorthand properties into their constituent parts:

    • Margin & Padding: Supports margin: '10 20 30 40' (top, right, bottom, left) and marginHorizontal/marginVertical.
    • Border: Expands border: '2 solid red' into borderTopWidth, borderTopStyle, borderTopColor, etc. Also expands borderRadius into all four corner radius properties.
    • Flex: Expands flex: '1 0 auto' into flexGrow, flexShrink, and flexBasis.
    • Gap: Expands gap: '10 20' into rowGap and columnGap.
    • Object Position: Expands objectPosition: '50% 25%' into objectPositionX: 0.5 and objectPositionY: 0.25.
    • Transform Origin: Expands transformOrigin: 'center top' into transformOriginX: '50%' and transformOriginY: '0%'.
  6. Apply styles using Media Queries

    master

    You can apply styles conditionally based on the container's dimensions and orientation using @media keys within your style object.

    Supported media features:

    • min-width / max-width
    • min-height / max-height
    • orientation (portrait | landscape)

    Example:

    const style = {
      fontSize: 12,
      '@media max-width: 500': {
        fontSize: 10,
      },
      '@media orientation: landscape': {
        flexDirection: 'row',
      },
    };
  7. How @react-pdf/stylesheet works

    master

    The @react-pdf/stylesheet engine transforms CSS-like style objects into normalized, resolved values suitable for PDF layout and rendering. It handles unit conversions (e.g., in, mm, vh), color parsing, shorthand expansion (e.g., margin, border), media queries, and style flattening.

    To use it, you provide a container object (defining dimensions and orientation) and a style object (or array of objects). The engine returns a computed object where all values are resolved.

    import stylesheet from '@react-pdf/stylesheet';
    
    const container = {
      width: 400,
      height: 600,
      orientation: 'portrait',
    };
    
    const style = {
      margin: 20,
      width: '50vw',
      height: '20vh',
      borderRadius: 5,
      fontWeight: 'semibold',
      borderBottom: '2 solid yellow',
      '@media max-width: 500': {
        backgroundColor: 'rgb(255, 0, 0)',
      },
    };
    
    const computed = stylesheet(container, style);
    
    // Result includes expanded properties like marginTop, borderBottomWidth, etc.
  8. Use PDF standard fonts

    master

    The following PDF standard fonts are pre-registered and available without any additional setup:

    • Helvetica (includes Bold, Oblique, and BoldOblique variants. Helvetica variants are pre-loaded by default).
    • Courier (includes Bold, Oblique, and BoldOblique variants).
    • Times-Roman (includes Bold, Italic, and BoldItalic variants).

    You can access them immediately using getFont().

    // Standard fonts are ready to use immediately
    const font = fontStore.getFont({
      fontFamily: 'Helvetica',
      fontWeight: 700,
      fontStyle: 'normal',
    });
  9. How react-pdf works: Creating a Document

    master

    To create a PDF, you define a component tree using specialized primitives: <Document>, <Page>, <View>, and <Text>. Styling is handled via StyleSheet.create, which follows a subset of CSS flexbox properties.

    Note: This package is for creating PDFs. If you need to display existing PDF files, use react-pdf instead.

    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 = () => (
      <Document>
        <Page size="A4" style={styles.page}>
          <View style={styles.section}>
            <Text>Section #1</Text>
          </View>
          <View style={styles.section}>
            <Text>Section #2</Text>
          </View>
        </Page>
      </Document>
    );
  10. Use Display vs Inline mode in <Math>

    master

    The <Math> component supports two rendering modes:

    1. Display mode (default): Renders the expression as a block, centered with larger operators. This is ideal for standalone equations.

      <Math>{"\\int_0^\\infty e^{-x^2} dx = \\sqrt{\\pi}"}</Math>
    2. Inline mode (inline prop): Renders compact expressions suitable for embedding within text lines.

      <View style={{ flexDirection: 'row', alignItems: 'center' }}>
        <Text>The equation </Text>
        <Math inline>{"E = mc^2"}</Math>
        <Text> is famous.</Text>
      </View>
  11. Understand the Node structure

    master

    A node represents a single element in a document. The root node must always be of type DOCUMENT, which contains PAGE nodes in its children array.

    Nodes are defined by the following properties:

    node.type (Mandatory)

    Specifies the type of the node. Types should be imported from @react-pdf/primitives.

    node.box

    Defines the bounding box for the node. Supported keys include:

    • left, top, width, height
    • paddingTop, paddingLeft, paddingBottom, paddingRight
    • marginTop, marginLeft, marginBottom, marginRight
    • borderTopWidth, borderLeftWidth, borderBottomWidth, borderRightWidth

    node.style

    Defines the visual appearance. Common supported properties include:

    • color, opacity, overflow, backgroundColor
    • borderTopLeftRadius, borderTopRightRadius, borderBottomLeftRadius, borderBottomRightRadius
    • borderTopColor, borderLeftColor, borderBottomColor, borderRightColor

    node.props

    Specific parameters required for certain nodes to behave correctly (e.g., SVG nodes).

  12. How the @react-pdf/render engine works

    master

    The @react-pdf/render library provides a render function that transforms a document tree (a nested structure of nodes) into a target context.

    Arguments:

    • ctx: The target context where the document is rendered. While currently targeting pdfkit document structures, it can target any structure that matches the pdfkit API. This allows for future multi-format rendering.
    • node: The document root node, which is a nested structure defining elements via type and associated properties.

    Important Note on Layout: This package does not handle node positioning, inheritance, style transformations, or layout logic. Its sole responsibility is to render the nodes exactly as provided into the context. When defining styles, use explicit properties like paddingTop instead of shorthand properties like padding.

    import render from '@react-pdf/render';
    import primitives from '@react-pdf/primitives';
    
    const view = {
      type: primitives.View,
      style: {
        backgroundColor: 'red',
        borderTopLeftRadius: 5,
      },
      box: {
        left: 20,
        top: 20,
        width: 100,
        height: 80,
      },
    };
    
    const doc = {
      type: primitives.Document,
      children: [
        {
          type: primitives.Page,
          box: { width: 400, height: 600 },
          children: [view],
        },
      ],
    };
    
    const ctx = createContext();
    render.default(ctx, doc);