Repository: diegomura/react-pdf-site Branch: master Commit: ea1fe9f5fd26 Files: 160 Total size: 1.2 MB Directory structure: gitextract_fs2i479s/ ├── .babelrc.js ├── .gitignore ├── .nvmrc ├── blog/ │ └── announcing-react-pdf-v2.md ├── docs/ │ ├── advanced.md │ ├── compatibility.md │ ├── components.md │ ├── debugging.md │ ├── document-navigation.md │ ├── dynamic-content.md │ ├── express.md │ ├── fonts.md │ ├── form.md │ ├── hooks.md │ ├── hyphenation.md │ ├── math.md │ ├── node.md │ ├── on-the-fly.md │ ├── orphan-widow-protection.md │ ├── page-wrapping.md │ ├── quick-start.md │ ├── rendering-process.md │ ├── styling.md │ ├── svg.md │ └── web-workers.md ├── env-config.js ├── examples/ │ ├── breakable-unbreakable.txt │ ├── checkbox.txt │ ├── circle.txt │ ├── clippath.txt │ ├── debugging.txt │ ├── disable-hyphenation.txt │ ├── disable-wrapping.txt │ ├── ellipse.txt │ ├── emoji.txt │ ├── fixed-components.txt │ ├── font-register.txt │ ├── formfield.txt │ ├── fractals.txt │ ├── g.txt │ ├── hyphenation-callback.txt │ ├── images.txt │ ├── inline-styles.txt │ ├── knobs.txt │ ├── line.txt │ ├── lineargradient.txt │ ├── math.txt │ ├── media-queries.txt │ ├── mixed-styles.txt │ ├── orphans-and-widows.txt │ ├── page-breaks.txt │ ├── page-numbers.txt │ ├── page-wrap.txt │ ├── path.txt │ ├── picker-formlist.txt │ ├── polygon.txt │ ├── polyline.txt │ ├── quick-start.txt │ ├── radialgradient.txt │ ├── rect.txt │ ├── resume.txt │ ├── styles.txt │ ├── svg.txt │ ├── svgtext.txt │ ├── text.txt │ └── textinput.txt ├── next.config.js ├── next.config_old.js ├── now.json ├── package.json ├── pages/ │ ├── _app.js │ ├── _document.js │ ├── advanced.js │ ├── blog/ │ │ └── [slug].js │ ├── compatibility.js │ ├── components.js │ ├── fonts.js │ ├── form.js │ ├── hooks.js │ ├── index.js │ ├── node.js │ ├── rendering-process.js │ ├── repl.js │ ├── styling.js │ └── svg.js ├── prettier.config.js ├── public/ │ ├── favicons/ │ │ ├── browserconfig.xml │ │ └── site.webmanifest │ ├── scripts/ │ │ └── pdf.worker.js │ └── styles/ │ ├── codemirror.css │ ├── fonts.css │ ├── index.css │ ├── prism.css │ └── tooltips.css └── src/ ├── components/ │ ├── Docs/ │ │ ├── DebugSample/ │ │ │ ├── DebugSample.js │ │ │ └── index.js │ │ ├── EditButton/ │ │ │ ├── EditButton.js │ │ │ └── index.js │ │ ├── GoToExample/ │ │ │ ├── GoToExample.js │ │ │ └── index.js │ │ ├── NavigationButtons/ │ │ │ ├── NavigationButtons.js │ │ │ └── index.js │ │ └── OverviewTimeline/ │ │ ├── OverviewTimeline.js │ │ └── index.js │ ├── Layout/ │ │ ├── GitHubIcon.js │ │ ├── Header.js │ │ ├── Layout.js │ │ ├── Menu.js │ │ ├── VersionPicker.js │ │ └── index.js │ ├── Repl/ │ │ ├── BackButton.js │ │ ├── Catch.js │ │ ├── CodeEditor.js │ │ ├── ErrorMessage.js │ │ ├── PDFViewer.js │ │ ├── PageNavigator.js │ │ ├── Repl.js │ │ ├── ReplFooter.js │ │ ├── ReplHeader.js │ │ └── index.js │ └── UI/ │ ├── Blockquote/ │ │ ├── Blockquote.js │ │ └── index.js │ ├── Button/ │ │ ├── Button.js │ │ └── index.js │ ├── Clipboard/ │ │ ├── Clipboard.js │ │ └── index.js │ ├── CodeBlock/ │ │ ├── CodeBlock.js │ │ └── index.js │ ├── Heading/ │ │ ├── Heading.js │ │ └── index.js │ ├── Icon/ │ │ ├── Icon.js │ │ └── index.js │ ├── InlineCode/ │ │ ├── InlineCode.js │ │ └── index.js │ ├── Link/ │ │ ├── Link.js │ │ └── index.js │ ├── List/ │ │ ├── List.js │ │ └── index.js │ ├── ListItem/ │ │ ├── ListItem.js │ │ └── index.js │ ├── Logo/ │ │ ├── Logo.js │ │ └── index.js │ ├── PageBanner/ │ │ ├── PageBanner.js │ │ └── index.js │ ├── Paragraph/ │ │ ├── Paragraph.js │ │ └── index.js │ ├── Spinner/ │ │ ├── Spinner.js │ │ └── index.js │ ├── Table/ │ │ ├── Table.js │ │ └── index.js │ ├── ThematicBreak/ │ │ ├── ThematicBreak.js │ │ └── index.js │ └── Title/ │ ├── Title.js │ └── index.js ├── lib/ │ ├── compress.js │ ├── markdown.js │ ├── toLowerCase.js │ └── transpile.js └── styled/ ├── media.js └── theme.js ================================================ FILE CONTENTS ================================================ ================================================ FILE: .babelrc.js ================================================ const env = require('./env-config.js') module.exports = { presets: ['next/babel'], plugins: [ ["prismjs", { "languages": ["jsx", "bash"] }], ['transform-define', env] ] } ================================================ FILE: .gitignore ================================================ node_modules dist .DS_Store .env *.snap .vscode *.log .next ================================================ FILE: .nvmrc ================================================ 18 ================================================ FILE: blog/announcing-react-pdf-v2.md ================================================ export const metadata = { date: '04/06/2021', author: 'diegomura', title: 'Announcing react-pdf v2.0', image: { url: '/images/og-banner-v2.png', width: '950', height: '805' } } I'm very excited to announce **react-pdf 2.0** to the world! This is the culmination of almost an entire year of work and all the lessons learned since this project started [all the way back in October 2016](https://github.com/diegomura/react-pdf/commit/272212a6847ad737be8241c64dbca7ad5a95ae8e). It's crazy, I feel it was just yesterday when [I was announcing 1.0 as well](https://twitter.com/diegomura/status/1070743817232494592). In essence, this new 2.0 version is a full reimplementation of the library. Starting from scratch is always a risky move, especially when the previous version is stable and being used in production by many companies and developers. However, the more I thought about it, the more it made sense to go down this path. In this blog post, I would like to tell you about ideas behind the v2 and the problems it solves. **TL;DR** - React-pdf 2.0 is backwards compatible with v1, so you don't need to change anything from your existing project to start using it. If you're not interested in what changed internally, you can jump straight to the [what's new](#what's-new) or the [FAQ](#faq) section. ## Motivation ### 1. Separate Layout from Rendering Similarly to how web browsers work, react-pdf has two very distinguishable steps. The first is **layout**, the process of computing the coordinates of each node inside the document, transforming text into glyphs, computing image sizes, and anything in between. To keep concerns separated, it's very important for the layout process to be PDF agnostic, this means, not having to deal with the underlying complexities of the PDF format. After layout is computed, then we can move to the **rendering** phase, which is essentially drawing the nodes in the target PDF document. This step takes all the layout data for granted, it's all about dealing with PDF specific stuff, rendering borders, backgrounds, images, text, etc. You can see the benefits of having these two steps separate right away: easier development, testing and debugging, and even having the ability to export not just PDF but any other format in the future. However, in previous react-pdf implementations there was no code separation of these concerns whatsoever. Each node was responsible for how it should layout and render, implemented in the same place. Not to mention that creating the PDF instance was the first thing we did, and it wasn't used until the very end of the entire process. This needed to change. ### 2. Embracing Immutability One of the main causes of issues right now is dealing with the mutable nature of `react-reconciler` while having an asynchronous rendering process. The reconciler is React's piece responsible for transforming the JSX code into calls to the underlying platform you are working on. If you think about react-dom or react-native, mutability makes sense: you create native views once, and then it's all about changing those instances (e.g. changing some styling when the JSX changes). There's a state being shared in successive reconciler calls. PDFs are different. When anything inside the document changes, we need to recompute the entire document. There's no way to just "change the color of a PDF text" and keep everything else the same. Previous react-pdf versions dealt with this by keeping class instances in memory that knew how to clone themselves in some very complex ways, so each successive render could be "independent" from the previous one but also share these instances. Working with this, however, had become increasingly hard and was the cause of many bugs that were very difficult to track down. Under this perspective, immutability is a must have. If I could find a way of making the renderer work with immutable structures, it would not only make bugs easier to find, but also make each render truly independent from the previous or future ones. ### 3. Performance Boost I believe react-pdf could be much much faster than what the v1 currently is. Although it's already faster than other solutions out there, such as HTML-to-PDF for most use cases, my goal is to keep pushing this to the limit. There are some bottlenecks we can't avoid, such as assets fetching or Yoga layout time, but there's a lot of room for improvements. The old implementation made it very difficult to both measure and improve rendering times, at least without the risk of breaking something along the way. ### 4. Better Testing No need to explain the benefits of having extensive tests for an open-source library, especially those like react-pdf that support so many different features and CSS properties. Even though previous versions have many features tested, it was only possible to accomplish this by basically simulating an entire document from the top and seeing how it turned out to be. Doing that to test a simple margin is just too much. ## Solution Enough talking about problems. Let's now move onto solutions. ### 1. Redefining Rendering Process Most of the points mentioned above were only visible after having experienced how this library evolved over time, and spending a lot of time developing it and understanding what the pain points were. So I asked myself: knowing what I now know about this library, what would I've done differently? The first thing would've been rethinking the whole rendering process. As mentioned above, splitting layout from rendering makes a lot of sense. This could be easily achieved by moving all the PDF related logic to the end of the document creation pipeline. This also has an incredibly powerful side-effect: being able to produce other types of output besides PDF documents. Suddenly, a whole world of new possibilities opened in front of our eyes. Additionally, separating the text layout process from the rest of the pipeline turned out to be very helpful. Text layout is an incredibly complex task by itself, since it involves transforming chars into glyphs with the provided font, grouping those glyphs into lines intelligently, breaking words between lines, dealing with ligatures, orphan & widow protection, and the list goes on and on. ### 2. Functional Approach It's not that I dislike classes, but I believe that functional programming paradigms can help a lot in breaking the whole rendering process into smaller and testable bits. Functions are generally easier to understand, since they are all about inputs and outputs. Immutability is generally very easy to enforce as well. We were already following this approach on textkit, the library responsible for performing text layout, and the benefits were just amazing. Rarely something bad was reported about it, and it has a test coverage that with the current way of testing would've been simply impossible to achieve. At the same time, this meant having to rewrite or at least re-organize much of the logic, which is mostly unchanged. It was daunting at first, and I was afraid of the criticism if things that worked suddenly did not. Hopefully it will pay off. ## What's New But this new version is not just about internal changes! It also ships a lot of new features that are ready to use out of the box. ### SVG Support React-pdf now ships with a set of new primitives to render SVG images! This has been on the backburner since the beginning of this project, postponed for several different reasons throughout the years for it being challenging to implement with the previous implementation. And this is HUGE. Having SVG support opens this library to a whole new world of possibilities. This doesn't just mean being able to render your own SVG (such as your company logo or similar), but also building integrations with pre-existing libraries that output SVG, such as the popular chart library recharts. As a future reference, just bear in mind that react-pdf does not take the same React SVG primitives but their own, so you will need to transform from one to the other. Should be as simple as cloning elements. You can see this working [here](http://react-pdf.org/repl?example=svg). ### New Hook API React-pdf always tried to as simple to use as possible, without compromising flexibility and covering many different use cases. To achieve that, it ships with a `` component for those who just want to see the document in the browser, and `` and `` for more complex and custom interactions. However, it felt that something was missing. Because of that, react-pdf 2.0 introduces a `usePDF` hook to fill the remaining needs. Through it, you can access the blob, url and loading state of your document, and more importantly, have a finer control over when the document should re-render. That's something that wasn't possible before. I'm excited to see what interactions people build using this new API. Read more about the new `usePDF` hook [here](http://react-pdf.org/hooks). ### More styles supported Last but not least, a bunch of new CSS properties are supported, and more to come. New features include: - Rgb, rgba and cmyk color - Overflow - zIndex - Percent border radius - Better unit support ## Acknowledges I would like to especially thank all the people that helped accomplish such an important milestone for this library. There were more than 39 people that participated on the [2.0 pull request](https://github.com/diegomura/react-pdf/pull/617), discussing different approaches, helping testing and patiently waiting for this work to be finished. That was truly amazing and something I didn't expect when I started working on this. It's definitely not always easy to keep up with all the work this library demands, but other people's involvement in the project makes it way more enjoyable to work on. In addition, as a reminder for anyone using or excited about this project, kindly consider [donating to react-pdf](https://opencollective.com/react-pdf). It really makes the difference, helping this project to keep moving forward. ## FAQ ### Is the new version going to be incompatible with the old one? No! 2.0 will be backwards compatible. Because of this, there should be no reason to remain on v1. Please report any bugs to our issue tracker, preferably with a REPL link. ### Will the v1.X version still be maintained after 2.0 gets released? Unfortunately, no. If it's just a simple change or fix, a patch to v1 will definitely be released (especially during the transition to 2.0), but no major feature will be added to it. That is mostly due to a lack of time on my end. I hope we can focus efforts on the next version, which is better in many ways. ================================================ FILE: docs/advanced.md ================================================ import EditButton from '../src/components/Docs/EditButton' import NavigationButtons from '../src/components/Docs/NavigationButtons' import PageWrapping from './page-wrapping.md' import DocumentNavigation from './document-navigation.md' import OnTheFly from './on-the-fly.md' import OrphanWidowProtection from './orphan-widow-protection.md' import DynamicContent from './dynamic-content.md' import Hyphenation from './hyphenation.md' import Debugging from './debugging.md' import Express from './express.md' import WebWorkers from './web-workers.md' import Math from './math.md' ## Advanced ================================================ FILE: docs/compatibility.md ================================================ import EditButton from '../src/components/Docs/EditButton' import NavigationButtons from '../src/components/Docs/NavigationButtons' ### Compatibility with Node.js We currently test react-pdf against Node.js 18, 20, and 21 (latest minors), so these are the versions we recommend using. Chances are you may use react-pdf with older versions of Node.js as well, but we can't guarantee it will work as expected. ### Compatibility with Bun While we don't officially support Bun, we have received reports that it works well with react-pdf. ### Compatibility with React `@react-pdf/renderer` is compatible with React 16 (16.8.0 or later), React 17, React 18 and React 19 (since v4.1.0) ### Compatibility with Next.js In general, you may use react-pdf with Next.js regardless of the version. However, before Next.js 14.1.1, Next.js (App Router) suffered from a bug that caused the Next.js server to crash when using react-pdf. If you encounter: ``` TypeError: ba.Component is not a constructor ``` You should upgrade to Next.js 14.1.1 or later. If that's not possible, update your Next.js config like this: ```js const nextConfig = { // … experimental: { // … serverComponentsExternalPackages: ['@react-pdf/renderer'], }, }; ``` ### Compatibility with esbuild If you are using esbuild to bundle your react-pdf application in ESM mode, you may encounter an error: ``` __dirname is not defined in ES module scope ``` This is because our dependency, [Yoga layout](https://yogalayout.com/), uses `__dirname` in their code. This will be fixed by the upcoming release of Yoga layout, but for now, you can work around this issue by using the `inject` option in esbuild. Create a file called `cjs-shim.ts`: ```ts import { createRequire } from 'node:module'; import path from 'node:path'; import url from 'node:url'; globalThis.require = createRequire(import.meta.url); globalThis.__filename = url.fileURLToPath(import.meta.url); globalThis.__dirname = path.dirname(__filename); ``` Then, add it to your `esbuild.ts`: ```ts await esbuild.build({ // … inject: ['cjs-shim.ts'], }); ``` And you should be good to go! ================================================ FILE: docs/components.md ================================================ import EditButton from '../src/components/Docs/EditButton' import NavigationButtons from '../src/components/Docs/NavigationButtons' ## Components React-pdf follows the [React primitives](https://github.com/lelandrichardson/react-primitives) specification, making the learning process very straightforward if you come from another React environment (such as react-native). Additionally, it implements custom Component types that allow you to structure your PDF document. ### Document This component represents the PDF document itself. It _must_ be the root of your tree element structure, and under no circumstances should it be used as child of another react-pdf component. In addition, it should only have children of type ``. #### Valid props | Prop name | Description | Type | Default | |------------|:-----------------------------------------------------------------------:|------------------------------------------:|--------------:| | title | Sets title info on the document's metadata | _String_ | _undefined_ | | author | Sets author info on the document's metadata | _String_ | _undefined_ | | subject | Sets subject info on the document's metadata | _String_ | _undefined_ | | keywords | Sets keywords associated info on the document's metadata | _String_ | _undefined_ | | creator | Sets creator info on the document's metadata | _String_ | _"react-pdf"_ | | producer | Sets producer info on the document's metadata | _String_ | _"react-pdf"_ | | pdfVersion | Sets PDF version for generated document | _String_ | _"1.3"_ | | language | Sets PDF default language | _String_ | _undefined_ | | pageMode | Specifying how the document should be displayed when opened | [PageMode](/components#pagemode-type) | _useNone_ | | pageLayout | This controls how (some) PDF viewers choose to show pages | [PageLayout](/components#pagelayout-type) | _singlePage_ | | creationDate | Sets the creation date on the document's metadata | _Date_ | _undefined_ | | modificationDate | Sets the modification date on the document's metadata | _Date_ | _undefined_ | | ownerPassword | Sets an owner password on the document. Owner password is required for setting permissions | _String_ | _undefined_ | | userPassword | Sets a user password on the document. When set, viewers will ask for the password before opening the file | _String_ | _undefined_ | | permissions | Defines document permissions. Requires `ownerPassword` to be set. [See more](/components#permissions-type) | [Permissions](/components#permissions-type) | _undefined_ | | onRender | Callback after document renders. Receives document blob argument in web | _Function_ | _undefined_ | ##### PageMode type `pageMode` prop can take one of the following values. Take into account some viewers might ignore this setting. | Value | Description | |----------------|:--------------------------------------------------------------------------------:| | useNone | Neither document bookmarks nor thumbnail images visible | | useOutlines | Document bookmarks visible | | useThumbs | Thumbnail images visible | | fullScreen | Full-screen mode, with no menu bar, window controls, or any other window visible | | useOC | Optional content group panel visible | | useAttachments | Attachments panel visible | ##### Permissions type `permissions` prop accepts an object with the following optional boolean fields. All default to `true` when an owner password is set without specifying permissions. | Value | Description | |------------------------|:-------------------------------------------------------------------:| | printing | Whether the user can print the document | | modifying | Whether the user can modify the document | | copying | Whether the user can copy text and images | | annotating | Whether the user can add or modify annotations | | fillingForms | Whether the user can fill in form fields | | contentAccessibility | Whether content can be extracted for accessibility purposes | | documentAssembly | Whether the user can assemble the document (insert, rotate, delete pages) | ##### PageLayout type `pageLayout` prop can take one of the following values. Take into account some viewers might ignore this setting. | Value | Description | |----------------|:----------------------------------------------------------------------:| | singlePage | Display one page at a time | | oneColumn | Display the pages in one column | | twoColumnLeft | Display the pages in two columns, with odd numbered pages on the left | | twoColumnRight | Display the pages in two columns, with odd numbered pages on the right | | twoPageLeft | Display the pages two at a time, with odd-numbered pages on the left | | twoPageRight | Display the pages two at a time, with odd-numbered pages on the right | --- ### Page Represents single page inside the PDF documents, or a subset of them if using the wrapping feature. A `` can contain as many pages as you want, but ensures not rendering a page inside any component besides Document. #### Valid props | Prop name | Description | Type | Default | |-------------|:---------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|------------------------------------------------:|-------------:| | size | Defines page size. If _String_, must be one of the [available page sizes](https://github.com/diegomura/react-pdf/blob/master/packages/layout/src/page/getSize.ts). Height is optional, if ommited it will behave as "auto". | _String_, _Array_, _Number_, _Object_ | _"A4"_ | | orientation | Defines page orientation. _Valid values: "portrait" or "landscape"_ | _String_ | _"portrait"_ | | wrap | Enables page wrapping for this page. [See more](/advanced#page-wrapping) | _Boolean_ | _true_ | | style | Defines page styles. [See more](/styling) | _Object_, _Array_ | _undefined_ | | debug | Enables debug mode on page bounding box. [See more](/advanced#debugging) | _Boolean_ | _false_ | | dpi | Enables setting a custom DPI for page contents. | _Number_ | _72_ | | id | Destination ID to be linked to. [See more](/advanced#destinations) | _String_ | _undefined_ | | bookmark | Attach bookmark to element. [See more](/advanced#bookmarks) | _String_ or [Bookmark](/advanced#bookmark-type) | _undefined_ | --- ### View The most fundamental component for building a UI and is designed to be nested inside other views and can have 0 to many children. #### Valid props | Prop name | Description | Type | Default | |-----------|:------------------------------------------------------------------------------:|------------------------------------------------:|------------:| | wrap | Enable/disable page wrapping for element. [See more](/advanced#page-wrapping) | _Boolean_ | _true_ | | style | Defines view styles. [See more](/styling) | _Object_, _Array_ | _undefined_ | | render | Render dynamic content based on context. [See more](/advanced#dynamic-content) | _Function_ | _undefined_ | | debug | Enables debug mode on view bounding box. [See more](/advanced#debugging) | _Boolean_ | _false_ | | fixed | Render component in all wrapped pages. [See more](/advanced#page-wrapping) | _Boolean_ | _false_ | | id | Destination ID to be linked to. [See more](/advanced#destinations) | _String_ | _undefined_ | | bookmark | Attach bookmark to element. [See more](/advanced#bookmarks) | _String_ or [Bookmark](/advanced#bookmark-type) | _undefined_ | --- ### Image A React component for displaying network or local (Node only) JPG or PNG images, as well as base64 encoded image strings. #### Valid props | Prop name | Description | Type | Default | |-----------|:---------------------------------------------------------------------------:|------------------------------------------------:|------------:| | src | Source of the image. [See more](/components#source-object) | _Source object_ | _undefined_ | | source | Alias of _src_. [See more](/components#source-object) | _Source object_ | _undefined_ | | style | Defines view styles. [See more](/styling) | _Object_, _Array_ | _undefined_ | | debug | Enables debug mode on view bounding box. [See more](/advanced#debugging) | _Boolean_ | _false_ | | fixed | Renders component in all wrapped pages. [See more](/advanced#page-wrapping) | _Boolean_ | _false_ | | cache | Enables image caching between consecutive renders | _Boolean_ | _true_ | | srcSet | Responsive image sources for resolution-based selection. E.g. `"small.jpg 300w, medium.jpg 600w"` | _String_ | _undefined_ | | sizes | Display width used for `srcSet` source selection | _String_, _Number_ | _undefined_ | | bookmark | Attach bookmark to element. [See more](/advanced#bookmarks) | _String_ or [Bookmark](/advanced#bookmark-type) | _undefined_ | ##### Source object Defines the source of an image. Can be in any of these four valid forms: | Form type | Description | Example | |-------------|:-----------------------------------------------------------------------------------------------------------------------------------:|------------------------------------------------------------| | String | Valid image URL or filesystem path (Node only) | `www.react-pdf.org/test.jpg` | | URL object | Enables to pass extra parameters on how to fetch images | `{ uri: valid-url, method: 'GET', headers: {}, body: '', credentials: 'include' }` | | Buffer | Renders image directly from Buffer. Image format (png or jpg) will be guessed based on Buffer. | `Buffer` | | Data buffer | Renders buffer image via the _data_ key. It's also recommended to provide the image _format_ so the engine knows how to proccess it | `{ data: Buffer, format: 'png' \| 'jpg' }` | | Function | A function that returns (can also return a promise that resolves to) any of the above formats | `() => String \| Promise` | --- ### ImageBackground A React component for displaying an image behind child content. It works like `Image` but acts as a container — any children are rendered on top of the image. #### Valid props | Prop name | Description | Type | Default | |------------|:---------------------------------------------------------------------------:|------------------------------------------------:|------------:| | src | Source of the image. [See more](/components#source-object) | _Source object_ | _undefined_ | | source | Alias of _src_. [See more](/components#source-object) | _Source object_ | _undefined_ | | style | Defines view styles. [See more](/styling) | _Object_, _Array_ | _undefined_ | | imageStyle | Defines styles applied to the background image | _Object_, _Array_ | _undefined_ | | debug | Enables debug mode on view bounding box. [See more](/advanced#debugging) | _Boolean_ | _false_ | | fixed | Renders component in all wrapped pages. [See more](/advanced#page-wrapping) | _Boolean_ | _false_ | | cache | Enables image caching between consecutive renders | _Boolean_ | _true_ | | srcSet | Responsive image sources for resolution-based selection | _String_ | _undefined_ | | sizes | Display width used for `srcSet` source selection | _String_, _Number_ | _undefined_ | | bookmark | Attach bookmark to element. [See more](/advanced#bookmarks) | _String_ or [Bookmark](/advanced#bookmark-type) | _undefined_ | --- ### Text A React component for displaying text. Text supports nesting of other Text or Link components to create inline styling. #### Valid props | Prop name | Description | Type | Default | |---------------------|:---------------------------------------------------------------------------------------:|------------------------------------------------:|------------:| | wrap | Enables/disables page wrapping for element. [See more](/advanced#page-wrapping) | _Boolean_ | _true_ | | render | Renders dynamic content based on context. [See more](/advanced#dynamic-content) | _Function_ | _undefined_ | | style | Defines view styles. [See more](/styling) | _Object_, _Array_ | _undefined_ | | debug | Enables debug mode on view bounding box. [See more](/advanced#debugging) | _Boolean_ | _false_ | | fixed | Renders component in all wrapped pages. [See more](/advanced#page-wrapping) | _Boolean_ | _false_ | | hyphenationCallback | Specify hyphenation callback at a text level. See [hypthenation](/advanced#hyphenation) | _Function_ | _undefined_ | | id | Destination ID to be linked to. [See more](/advanced#destinations) | _String_ | _undefined_ | | bookmark | Attach bookmark to element. [See more](/advanced#bookmarks) | _String_ or [Bookmark](/advanced#bookmark-type) | _undefined_ | --- ### Link A React component for displaying an hyperlink. Link’s can be nested inside a Text component, or being inside any other valid primitive. #### Valid props | Prop name | Description | Type | Default | |-----------|:---------------------------------------------------------------------------------------------:|------------------------------------------------:|------------:| | src | Valid URL or destination ID. ID must be prefixed with `#`. [See more](/advanced#destinations) | _String_ | _undefined_ | | href | Alias of _src_. Valid URL for external links | _String_ | _undefined_ | | wrap | Enable/disable page wrapping for element. [See more](/advanced#page-wrapping) | _Boolean_ | _true_ | | style | Defines view styles. [See more](/styling) | _Object_, _Array_ | _undefined_ | | debug | Enables debug mode on view bounding box. [See more](/advanced#debugging) | _Boolean_ | _false_ | | fixed | Render component in all wrapped pages. [See more](/advanced#page-wrapping) | _Boolean_ | _false_ | | hitSlop | Expands the clickable area beyond the visible bounds of the link | _Number_ or _Object_ `{ top, bottom, left, right }` | _undefined_ | | bookmark | Attach bookmark to element. [See more](/advanced#bookmarks) | _String_ or [Bookmark](/advanced#bookmark-type) | _undefined_ | --- ### Note A React component for displaying a note annotation inside the document. #### Valid props | Prop name | Description | Type | Default | |-----------|:---------------------------------------------------------------------------:|------------------:|------------:| | style | Defines view styles. [See more](/styling) | _Object_, _Array_ | _undefined_ | | children | Note string content | _String_ | _undefined_ | | fixed | Renders component in all wrapped pages. [See more](/advanced#page-wrapping) | _Boolean_ | _false_ | --- ### Canvas A React component for freely drawing any content on the page. #### Valid props | Prop name | Description | Type | Default | |-----------|:---------------------------------------------------------------------------:|------------------------------------------------:|------------:| | style | Defines view styles. [See more](/styling) | _Object_, _Array_ | _undefined_ | | paint | Painter function | _Function_ | _undefined_ | | debug | Enables debug mode on view bounding box. [See more](/advanced#debugging) | _Boolean_ | _false_ | | fixed | Renders component in all wrapped pages. [See more](/advanced#page-wrapping) | _Boolean_ | _false_ | | bookmark | Attach bookmark to element. [See more](/advanced#bookmarks) | _String_ or [Bookmark](/advanced#bookmark-type) | _undefined_ | React-pdf does not check how much space your drawing takes, so make sure you always define a `width` and `height` on the `style` prop. ##### Painter function Prop used to perform drawings inside the Canvas. It takes 3 arguments: - `Painter object`: Wrapper around _pdfkit_ drawing methods. Use this to draw inside the Canvas - `availableWidth`: Width of the Canvas element. - `availableHeight`: Height of the Canvas element. ##### Painter object Wrapper around _pdfkit_ methods you can use to draw inside the Canvas. All operations are chainable. For more information about how these methods work, please refer to [pdfkit documentation](http://pdfkit.org/). Available methods: - dash - clip - save - path - fill - font - text - rect - scale - moveTo - lineTo - stroke - rotate - circle - lineCap - opacity - ellipse - polygon - restore - lineJoin - fontSize - fillColor - lineWidth - translate - miterLimit - strokeColor - fillOpacity - roundedRect - strokeOpacity - bezierCurveTo - quadraticCurveTo - linearGradient - radialGradient --- ### PDFViewer `Web only` Iframe PDF viewer for client-side generated documents. #### Valid props | Prop name | Description | Type | Default | |-------------|:--------------------------------------------------------:|-------------------:|------------:| | style | Defines iframe styles | _Object_, _Array_ | _undefined_ | | className | Defines iframe class name | _String _ | _undefined_ | | children | PDF document implementation | _Document_ | _undefined_ | | width | Width of embedded PDF iframe | _String_, _Number_ | _undefined_ | | height | Height of embedded PDF iframe | _String_, _Number_ | _undefined_ | | innerRef | Ref to the underlying iframe element | _Ref_ | _undefined_ | | showToolbar | Render the toolbar. Supported on Chrome, Edge and Safari | _Boolean_ | _true_ | Other props are passed through to the iframe. --- ### PDFDownloadLink `Web only` Anchor tag to enable generate and download PDF documents on the fly. Refer to [on the fly rendering](/advanced#on-the-fly-rendering) for more information. #### Valid props | Prop name | Description | Type | Default | |-----------|:-----------------------------:|-----------------------:|------------:| | document | PDF document implementation | _Document_ | _undefined_ | | fileName | Download PDF file name | _String_ | _undefined_ | | style | Defines anchor tag styles | _Object_, _Array_ | _undefined_ | | className | Defines anchor tag class name | _String_ | _undefined_ | | children | Anchor tag content | _DOM node_, _Function_ | _undefined_ | | onClick | Click handler. Receives click event and PDF instance as arguments | _Function_ | _undefined_ | --- ### BlobProvider `Web only` Easy and declarative way of getting document's blob data without showing it on screen. Refer to [on the fly rendering](/advanced#on-the-fly-rendering) for more information. #### Valid props | Prop name | Description | Type | Default | |-----------|:----------------------------------------------------------------:|-----------:|------------:| | document | PDF document implementation | _Document_ | _undefined_ | | children | Render prop with blob, url, error and loading state as arguments | _Function_ | _undefined_ | --- ================================================ FILE: docs/debugging.md ================================================ import DebugSample from '../src/components/Docs/DebugSample' import GoToExample from '../src/components/Docs/GoToExample' ### Debugging React-pdf ships a built-in debugging system you can use whenever you have doubts about how elements are being laid out on the page. All you have to do is to set the `debug` prop to `true` on any valid primitive (except _Document_) and re-render the document to see the result on the screen. --- ================================================ FILE: docs/document-navigation.md ================================================ ### Document Navigation There are two main ways to make a document navigable: #### Destinations `v2.0.0` Destinations are the simplest form of navigation. They allow to create interactive links that take the user directly to the defined place within the document. A destination can be created by setting the `id` prop to a _String_ on any supported element ([see more](/components)). After that, the destination can be linked to by setting the `src` prop on the `` element to the same _String_, but with the leading hash (`#`) symbol: ```js import { Document, Link, Page, Text } from '@react-pdf/renderer' const doc = () => ( // Notice the hash symbol Click me to get to the footnote // Other content here // No hash symbol You are here because you clicked the link above ); ``` #### Bookmarks `v2.2.0` Bookmarks allow the user to navigate interactively from one part of the document to another. They form a tree-structured hierarchy of items, which serve as a visual table of contents to display the document’s structure to the user. A bookmark can be defined by the `bookmark` prop on any of the supported components ([see more](/components)), and can take the form of either a _String_ or a _Bookmark_ type ```js import { Document, Page, Text } from '@react-pdf/renderer' const doc = () => ( {...} ); ``` The example above will create a table of content of 2 nested items: The parent will be the book's name, and the child the chapter's name. You can nest as many bookmarks as you want. Note that some older PDF viewers may not support bookmarks. ##### Bookmark type Object that matches the following schema: | Value | Description | Type | |-----------------------|:-----------------------------------------------------------------------------------:|----------:| | title | Bookmark value | _String_ | | top _(Optional)_ | Y coodinate from the document top edge where user get's redirected. Defaults to 0 | _Number_ | | left _(Optional)_ | X coodinate from the document top edge where user get's redirected. Defaults to 0 | _Number_ | | zoom _(Optional)_ | Reader zoom value after clicking on the bookmark | _Number_ | | fit _(Optional)_ | Redirect user to the start of the page | _Boolean_ | | expanded _(Optional)_ | Viewer should expand tree node in table of contents (not supported in some viewers) | _Boolean_ | --- ================================================ FILE: docs/dynamic-content.md ================================================ import GoToExample from '../src/components/Docs/GoToExample' ### Dynamic content With react-pdf, now it is possible to render dynamic text based on the context in which a certain element is being rendered. All you have to do is to pass a function to the `render` prop of the `` or `` component. The result will be rendered inside the text block as a child. ``` import { Document, Page } from '@react-pdf/renderer' const doc = () => ( ( `${pageNumber} / ${totalPages}` )} fixed /> ( pageNumber % 2 === 0 && ( I'm only visible in odd pages! ) )} /> ); ``` #### Available arguments | Name | Description | Type | | ---------------------- | :-----------------------------------------: | --------: | | pageNumber | Current page number | _Integer_ | | totalPages `Text only` | Total amount of pages in the final document | _Integer_ | | subPageNumber | Current subpage in the Page component | _Integer_ | | subPageTotalPages `Text only` | Total amount of pages in the Page component | _Integer_ | Bear in mind that the `render` function is called twice for `` elements: once for layout on the page wrapping process, and another one after it's know how many pages the document will have. > **Protip:** Use this API in conjunction with fixed elements to render page number indicators --- ================================================ FILE: docs/express.md ================================================ ### Usage with Express.js `node only` ```jsx import React from 'react'; import ReactPDF from '@react-pdf/renderer'; const pdfStream = await ReactPDF.renderToStream(); res.setHeader('Content-Type', 'application/pdf'); pdfStream.pipe(res); pdfStream.on('end', () => console.log('Done streaming, response sent.')); ``` ================================================ FILE: docs/fonts.md ================================================ import EditButton from '../src/components/Docs/EditButton' import GoToExample from '../src/components/Docs/GoToExample' import NavigationButtons from '../src/components/Docs/NavigationButtons' ## Fonts React-pdf is shipped with a `Font` module that enables to load fonts from different sources, handle how words are wrapped and defined an emoji source to embed these glyphs on your document. You can define multiple sources for the same font family, each with a different `fontStyle` or `fontWeight`. React-pdf will pick the appropriate font for each `` based on its style and the registered fonts. Currently, - [only TTF and WOFF fonts files are supported](https://github.com/diegomura/react-pdf/issues/334). A list of available TTF fonts from Google can be found [here](https://gist.github.com/sadikay/d5457c52e7fb2347077f5b0fe5ba9300). - Any OpenType Variable fonts (such as Noto Sans variable weights font) does not work properly because PDF 2.0 spec does not support those. It is required to register separate fonts using 'fonts' property (explained in below). ``` import { StyleSheet, Font } from '@react-pdf/renderer' // Register font Font.register({ family: 'Roboto', src: source }); // Reference font const styles = StyleSheet.create({ title: { fontFamily: 'Roboto' } }) ``` --- ### `register` Fonts really make the difference when it comes on styling a document. For obvious reasons, react-pdf cannot ship a wide amount of them. Here's a list of available font families that are supported out of the box: - `Courier` - `Courier-Bold` - `Courier-Oblique` - `Courier-BoldOblique` - `Helvetica` - `Helvetica-Bold` - `Helvetica-Oblique` - `Helvetica-BoldOblique` - `Times-Roman` - `Times-Bold` - `Times-Italic` - `Times-BoldItalic` In case you want to use a different font, you may load additional font files from many different sources via the `register` method very easily. ``` import { Font } from '@react-pdf/renderer' Font.register({ family: 'FamilyName', src: source, fontStyle: 'normal', fontWeight: 'normal', fonts?: [] }); ``` #### source Specifies the source of the font. This can either be a valid URL, or an absolute path if you're using react-pdf on Node. #### family Name to which the font will be referenced on styles definition. Can be any unique valid string #### fontStyle Specifies to which font style the registered font refers to. | Value | Description | | ------- | :------------------------------------------------------------------------------------------------------------------------------------------------------ | | normal | Selects a font that is classified as normal _Default_ | | italic | Selects a font that is classified as italic. If no italic version of the font is registered, react-pdf will fail when a style of this type is present | | oblique | Selects a font that is classified as oblique. If no oblique version of the font is registered, react-pdf will fail when a style of this type is present | #### fontWeight Specifies the registered font weight. | Value | Description | | ---------- | :----------------------------------- | | thin | Equals to value 100 | | ultralight | Equals to value 200 | | light | Equals to value 300 | | normal | Equals to value 400 _Default_ | | medium | Equals to value 500 | | semibold | Equals to value 600 | | bold | Equals to value 700 | | ultrabold | Equals to value 800 | | heavy | Equals to value 900 | | _number_ | Any integer value between 0 and 1000 | When the exact font weight is not registered for a given text, react-pdf will fallback to the nearest registered weight in the same way browsers do. More information [here](https://developer.mozilla.org/en-US/docs/Web/CSS/font-weight#Fallback_weights) #### fonts In many cases you will end up registering multiple sources for the same font family (each with different font-style and font-weight for instance). As an alternative of calling `Font.register` for each of this, you can use the `fonts` attribute to register them all at once: ``` Font.register({ family: 'Roboto', fonts: [ { src: source1 }, // font-style: normal, font-weight: normal { src: source2, fontStyle: 'italic' }, { src: source3, fontStyle: 'italic', fontWeight: 700 }, ]}); ``` --- ### `registerHyphenationCallback` Enables you to have fine-grained control over how words break, passing your own callback and handle all that logic for yourself: ``` import { Font } from '@react-pdf/renderer' const hyphenationCallback = (word) => { // Return word parts in an array } Font.registerHyphenationCallback(hyphenationCallback); ``` #### Disabling hyphenation You can easily disable word hyphenation by just returning the same word as it is passed to the hyphenation callback ``` Font.registerHyphenationCallback(word => [word]); ``` --- ### `registerEmojiSource` PDF documents do not support color emoji fonts. This is a bummer for the ones out there who love their expressiveness and simplicity. The only way of rendering this glyphs on a PDF document, is by embedding them as images. React-pdf makes this task simple by enabling you to use a CDN from where to download emoji images. All you have to do is setup a valid URL (we recommend using [Twemoji](https://github.com/twitter/twemoji) for this task), and react-pdf will take care of the rest: ``` import { Font } from '@react-pdf/renderer' Font.registerEmojiSource({ format: 'png', url: 'https://cdnjs.cloudflare.com/ajax/libs/twemoji/14.0.2/72x72/', }); ``` > **Protip:** react-pdf will need a internet connection to download emoji's images at render time, so bare that in mind when choosing to use this API ================================================ FILE: docs/form.md ================================================ import EditButton from '../src/components/Docs/EditButton' import GoToExample from '../src/components/Docs/GoToExample' import NavigationButtons from '../src/components/Docs/NavigationButtons' ## Forms React-pdf includes the ability to use [AcroForm](https://experienceleague.adobe.com/en/docs/experience-manager-learn/forms/document-services/pdf-forms-and-documents#acroforms)-Forms in pdfs. AcroForm is part of interactive pdfs and includes annotations for e.g. text fields, checkboxes. The AcroForm is automatically initialized as soon as one of the form elements is used. ### TextInput The `` element represents a text field for inputting single- or multiline text. #### Valid props | Prop name | Description | Type | Default | | --------- | :----------------------------------------------------------------: | ------------------------------------------: | ----------: | | align | Defines the alignment of text | _String_ | _left_ | | multiline | Defines if the user is allowed to input more than one line of text | _Boolean_ | _false_ | | password | If set to true the text will be masked with e. g. * | _Boolean_ | _false_ | | noSpell | If set to true tells the pdf viewer to not spellcheck the text | _Boolean_ | _false_ | | format | Defines the format the textinput should be formatted to | [TextInputFormatting](#textinputformatting) | _undefined_ | | fontSize | Defines the font size for the text input. Set to `0` for auto-size | _Number_ | _undefined_ | | maxLength | Defines the maximum number of characters | _Number_ | _undefined_ | See also [Common Form Attributes](#common-form-attributes) ##### TextInputFormatting `format` is a definition how the value shall be formatted by the viewer. Take into account that not all viewers support this feature because it involves javascript execution. | Prop name | Description | Type | Default | | --------------- | :--------------------------------------------------: | ------------------------------------------: | ----------: | | type | Defines the alignment of text | [TextInputFormatType](#textinputformattype) | _undefined_ | | param | Defines a format for certain types | _String_ | _undefined_ | | nDec | Defines the number of places after the decimal point | _Number_ | _undefined_ | | sepComma | Defines if the seperator shall be a comma or not | _Boolean_ | _false_ | | negStyle | Defines style for negative numbers | _String_ | _undefined_ | | currency | Defines the symbol to be placed as currency sign | _String_ | _undefined_ | | currencyPrepend | If set to true the currency sign is prepended | _Boolean_ | _false_ | ##### TextInputFormatType `type` prop can take one of the following values. | Value | Description | | -------- | :-----------------------------------------------------------------: | | date | Expects the param prop to be a valid date format. | | time | Expects the param prop to be a valid time format. | | percent | Uses the props nDec, sepComma, negStyle, currency, currencyPrepend. | | number | Uses the props nDec, sepComma, negStyle, currency, currencyPrepend. | | zip | Formats for the zip-code standard | | zipPlus4 | Formats for the zip+4 standard | | phone | Formats for a phone number | | ssn | Formats for a ssn number | For deeper knowledge into the formatting you might want to look into the [pdfkit doc](https://pdfkit.org/docs/forms.html#text_field_formatting) and into the [API Reference for Forms](https://experienceleague.adobe.com/docs/experience-manager-learn/assets/FormsAPIReference.pdf) Page 119. --- ### Checkbox The `` element represents one of two states the user can toggle between. Some viewers behave differently based on wether the `name` prop is set or not and wether there are name duplicates or not. This can result in inconsistencies which makes the `name` prop recommendable to use and to achieve a consistent result across various viewers. #### Valid props | Prop name | Description | Type | Default | | --------------- | :--------------------------------------------------------------------------: | --------: | ----------: | | backGroundColor | It defines the color of the inside of the checkbox it applies to | _String_ | _undefined_ | | borderColor | Defines the color used to paint the outline of the checkbox | _String_ | _undefined_ | | checked | If set to true the checkbox is checked | _Boolean_ | _false_ | | onState | If set to true tells the pdf viewer to not spellcheck the text | _String_ | _Yes_ | | offState | Defines the format the textinput should be formatted to | _String_ | _No_ | | xMark | If set to true the onState appears as a X otherwise a checkmark is displayed | _Boolean_ | _false_ | See also [Common Form Attributes](#common-form-attributes) --- ### Select The ` ); ReactPDF.render(doc); ================================================ FILE: examples/line.txt ================================================ const styles = StyleSheet.create({ page: { padding: 60 }, }); const doc = ( ); ReactPDF.render(doc); ================================================ FILE: examples/lineargradient.txt ================================================ const styles = StyleSheet.create({ page: { padding: 60 }, }); const doc = ( ); ReactPDF.render(doc); ================================================ FILE: examples/math.txt ================================================ const styles = StyleSheet.create({ page: { padding: 40, backgroundColor: '#fafafa', }, title: { fontSize: 18, fontWeight: 'bold', marginBottom: 4, color: '#1a1a1a', }, subtitle: { fontSize: 9, color: '#888', marginBottom: 20, }, card: { backgroundColor: 'white', borderRadius: 5, padding: 12, marginBottom: 8, borderWidth: 1, borderColor: '#e8e8e8', }, cardLabel: { fontSize: 8, color: '#999', marginBottom: 6, textTransform: 'uppercase', letterSpacing: 0.5, }, row: { flexDirection: 'row', gap: 8, marginBottom: 8, }, halfCard: { flex: 1, backgroundColor: 'white', borderRadius: 5, padding: 12, borderWidth: 1, borderColor: '#e8e8e8', }, inlineRow: { flexDirection: 'row', alignItems: 'center', }, inlineText: { fontSize: 10, color: '#333', }, footer: { marginTop: 'auto', paddingTop: 12, borderTopWidth: 1, borderTopColor: '#e8e8e8', flexDirection: 'row', justifyContent: 'space-between', }, footerText: { fontSize: 7, color: '#aaa', }, }); const doc = ( Mathematical Typesetting LaTeX expressions rendered as vector graphics via @react-pdf/math Quadratic Formula {'x = \\frac{-b \\pm \\sqrt{b^2 - 4ac}}{2a}'} Euler's Identity {'e^{i\\pi} + 1 = 0'} Limits {'\\lim_{x \\to 0} \\frac{\\sin x}{x} = 1'} Gaussian Integral {'\\int_{-\\infty}^{\\infty} e^{-x^2} dx = \\sqrt{\\pi}'} Basel Problem {'\\sum_{n=1}^{\\infty} \\frac{1}{n^2} = \\frac{\\pi^2}{6}'} Matrix Notation {'A = \\begin{pmatrix} a_{11} & a_{12} \\\\ a_{21} & a_{22} \\end{pmatrix}'} Binomial Theorem {'(x + y)^n = \\sum_{k=0}^{n} \\binom{n}{k} x^{n-k} y^k'} Maxwell's Equation (Faraday's Law) {'\\nabla \\times \\vec{E} = -\\frac{\\partial \\vec{B}}{\\partial t}'} Inline Usage The famous equation {'E = mc^2'} relates mass and energy. Generated with @react-pdf/math Powered by MathJax ); ReactPDF.render(doc); ================================================ FILE: examples/media-queries.txt ================================================ const styles = StyleSheet.create({ body: { padding: 35, }, content: { padding: 20, '@media max-width: 400': { flexDirection: 'column', }, '@media min-width: 400': { flexDirection: 'row', }, }, block: { height: 150, width: 150, backgroundColor: 'red', }, }); const MediaComponent = () => ( ); const doc = ( ); ReactPDF.render(doc); ================================================ FILE: examples/mixed-styles.txt ================================================ const styles = StyleSheet.create({ page: { backgroundColor: 'tomato' }, section: { textAlign: 'center', margin: 30 } }); const doc = ( Section #1 ); ReactPDF.render(doc); ================================================ FILE: examples/orphans-and-widows.txt ================================================ const styles = StyleSheet.create({ page: { padding: 60 }, text: { margin: 12, fontSize: 14, textAlign: 'justify', fontFamily: 'Times-Roman' }, }); const doc = ( Widows example. Try changing prop value En un lugar de la Mancha, de cuyo nombre no quiero acordarme, no ha mucho tiempo que vivía un hidalgo de los de lanza en astillero, adarga antigua, rocín flaco y galgo corredor. Una olla de algo más vaca que carnero, salpicón las más noches, duelos y quebrantos los sábados, lentejas los viernes, algún palomino de añadidura los domingos, consumían las tres partes de su hacienda. El resto della concluían sayo de velarte, calzas de velludo para las fiestas con sus pantuflos de lo mismo, los días de entre semana se honraba con su vellori de lo más fino. Tenía en su casa una ama que pasaba de los cuarenta, y una sobrina que no llegaba a los veinte, y un mozo de campo y plaza, que así ensillaba el rocín como tomaba la podadera. Frisaba la edad de nuestro hidalgo con los cincuenta años, era de complexión recia, seco de carnes, enjuto de rostro; gran madrugador y amigo de la caza. Quieren decir que tenía el sobrenombre de Quijada o Quesada (que en esto hay alguna diferencia en los autores que deste caso escriben), aunque por conjeturas verosímiles se deja entender que se llama Quijana; pero esto importa poco a nuestro cuento; basta que en la narración dél no se salga un punto de la verdad Orphans example. Try changing prop value En un lugar de la Mancha, de cuyo nombre no quiero acordarme, no ha mucho tiempo que vivía un hidalgo de los de lanza en astillero, adarga antigua, rocín flaco y galgo corredor. Una olla de algo más vaca que carnero, salpicón las más noches, duelos y quebrantos los sábados, lentejas los viernes, algún palomino de añadidura los domingos, consumían las tres partes de su hacienda. El resto della concluían sayo de velarte, calzas de velludo para las fiestas con sus pantuflos de lo mismo, los días de entre semana se honraba con su vellori de lo más fino. Tenía en su casa una ama que pasaba de los cuarenta, y una sobrina que no llegaba a los veinte, y un mozo de campo y plaza, que así ensillaba el rocín como tomaba la podadera. Frisaba la edad de nuestro hidalgo con los cincuenta años, era de complexión recia, seco de carnes, enjuto de rostro; gran madrugador y amigo de la caza. Quieren decir que tenía el sobrenombre de Quijada o Quesada (que en esto hay alguna diferencia en los autores que deste caso escriben), aunque por conjeturas verosímiles se deja entender que se llama Quijana; pero esto importa poco a nuestro cuento; basta que en la narración dél no se salga un punto de la verdad ); ReactPDF.render(doc); ================================================ FILE: examples/page-breaks.txt ================================================ const Quixote = () => ( Don Quijote de la Mancha Miguel de Cervantes Capítulo I: Que trata de la condición y ejercicio del famoso hidalgo D. Quijote de la Mancha En un lugar de la Mancha, de cuyo nombre no quiero acordarme, no ha mucho tiempo que vivía un hidalgo de los de lanza en astillero, adarga antigua, rocín flaco y galgo corredor. Una olla de algo más vaca que carnero, salpicón las más noches, duelos y quebrantos los sábados, lentejas los viernes, algún palomino de añadidura los domingos, consumían las tres partes de su hacienda. El resto della concluían sayo de velarte, calzas de velludo para las fiestas con sus pantuflos de lo mismo, los días de entre semana se honraba con su vellori de lo más fino. Tenía en su casa una ama que pasaba de los cuarenta, y una sobrina que no llegaba a los veinte, y un mozo de campo y plaza, que así ensillaba el rocín como tomaba la podadera. Frisaba la edad de nuestro hidalgo con los cincuenta años, era de complexión recia, seco de carnes, enjuto de rostro; gran madrugador y amigo de la caza. Quieren decir que tenía el sobrenombre de Quijada o Quesada (que en esto hay alguna diferencia en los autores que deste caso escriben), aunque por conjeturas verosímiles se deja entender que se llama Quijana; pero esto importa poco a nuestro cuento; basta que en la narración dél no se salga un punto de la verdad Instead of showing the title here Capítulo II: Que trata de la primera salida que de su tierra hizo el ingenioso Don Quijote It breaks to the top of the next page Hechas, pues, estas prevenciones, no quiso aguardar más tiempo a poner en efeto su pensamiento, apretándole a ello la falta que él pensaba que hacía en el mundo su tardanza, según eran los agravios que pensaba deshacer, tuertos que enderezar, sinrazones que emendar y abusos que mejorar y deudas que satisfacer. Y así, sin dar parte a persona alguna de su intención y sin que nadie le viese, una mañana, antes del día, que era uno de los calurosos del mes de Julio, se armó de todas sus armas, subió sobre Rocinante, puesta su mal compuesta celada, embrazó su adarga, tomó su lanza y por la puerta falsa de un corral salió al campo con grandísimo contento y alborozo de ver con cuánta facilidad había dado principio a su buen deseo. Mas apenas se vio en el campo cuando le asaltó un pensamiento terrible, y tal, que por poco le hiciera dejar la comenzada empresa; y fue que le vino a la memoria que no era armado caballero, y que, conforme a ley de caballería, ni podía ni debía tomar armas con ningún caballero; y puesto que lo fuera, había de llevar armas blancas, como novel caballero, sin empresa en el escudo, hasta que por su esfuerzo la ganase. Estos pensamientos le hicieron titubear en su propósito; mas pudiendo más su locura que otra razón alguna, propuso de hacerse armar caballero del primero que topase, a imitación de otros muchos que así lo hicieron, según él había leído en los libros que tal le tenían. En lo de las armas blancas, pensaba limpiarlas de manera, en teniendo lugar, que lo fuesen más que un arminio; y con esto se quietó18 y prosiguió su camino, sin llevar otro que aquel que su caballo quería, creyendo que en aquello consistía la fuerza de las aventuras ); Font.register({ family: 'Oswald', src: 'https://fonts.gstatic.com/s/oswald/v13/Y_TKV6o8WovbUd3m_X9aAA.ttf' }); const styles = StyleSheet.create({ body: { paddingTop: 35, paddingBottom: 65, paddingHorizontal: 35, }, title: { fontSize: 24, textAlign: 'center', fontFamily: 'Oswald' }, author: { fontSize: 12, textAlign: 'center', marginBottom: 40, }, subtitle: { fontSize: 18, margin: 12, fontFamily: 'Oswald' }, text: { margin: 12, fontSize: 14, textAlign: 'justify', fontFamily: 'Times-Roman' }, image: { marginVertical: 30, marginHorizontal: 100, }, emphasis: { margin: 12, fontSize: 24, color: '#F22300', fontFamily: 'Oswald' } }); ReactPDF.render(); ================================================ FILE: examples/page-numbers.txt ================================================ const styles = StyleSheet.create({ page: { padding: 60 }, box: { width: '100%', marginBottom: 30, borderRadius: 5 }, pageNumbers: { position: 'absolute', bottom: 20, left: 0, right: 0, textAlign: 'center' }, }); const doc = ( ( `${pageNumber} / ${totalPages}` )} fixed /> ); ReactPDF.render(doc); ================================================ FILE: examples/page-wrap.txt ================================================ const HR = () => ( ); const ChapterHeading = ({ number, children, ...props }) => ( {number} {children} ); const Quixote = () => ( Don Quijote de la Mancha Don Quijote de la Mancha
Miguel de Cervantes
Que trata de la condición y ejercicio del famoso hidalgo D. Quijote de la Mancha En un lugar de la Mancha, de cuyo nombre no quiero acordarme, no ha mucho tiempo que vivía un hidalgo de los de lanza en astillero, adarga antigua, rocín flaco y galgo corredor. Una olla de algo más vaca que carnero, salpicón las más noches, duelos y quebrantos los sábados, lentejas los viernes, algún palomino de añadidura los domingos, consumían las tres partes de su hacienda. El resto della concluían sayo de velarte, calzas de velludo para las fiestas con sus pantuflos de lo mismo, los días de entre semana se honraba con su vellori de lo más fino. Tenía en su casa una ama que pasaba de los cuarenta, y una sobrina que no llegaba a los veinte, y un mozo de campo y plaza, que así ensillaba el rocín como tomaba la podadera. Frisaba la edad de nuestro hidalgo con los cincuenta años, era de complexión recia, seco de carnes, enjuto de rostro; gran madrugador y amigo de la caza. Quieren decir que tenía el sobrenombre de Quijada o Quesada (que en esto hay alguna diferencia en los autores que deste caso escriben), aunque por conjeturas verosímiles se deja entender que se llama Quijana; pero esto importa poco a nuestro cuento; basta que en la narración dél no se salga un punto de la verdad. Es, pues, de saber, que este sobredicho hidalgo, los ratos que estaba ocioso (que eran los más del año) se daba a leer libros de caballerías con tanta afición y gusto, que olvidó casi de todo punto el ejercicio de la caza, y aun la administración de su hacienda; y llegó a tanto su curiosidad y desatino en esto, que vendió muchas hanegas de tierra de sembradura, para comprar libros de caballerías en que leer; y así llevó a su casa todos cuantos pudo haber dellos; y de todos ningunos le parecían tan bien como los que compuso el famoso Feliciano de Silva: porque la claridad de su prosa, y aquellas intrincadas razones suyas, le parecían de perlas; y más cuando llegaba a leer aquellos requiebros y cartas de desafío, donde en muchas partes hallaba escrito: la razón de la sinrazón que a mi razón se hace, de tal manera mi razón enflaquece, que con razón me quejo de la vuestra fermosura, y también cuando leía: los altos cielos que de vuestra divinidad divinamente con las estrellas se fortifican, y os hacen merecedora del merecimiento que merece la vuestra grandeza. "La razón de la sinrazón que a mi razón se hace, de tal manera mi razón enflaquece, que con razón me quejo de la vuestra fermosura." Con estas y semejantes razones perdía el pobre caballero el juicio, y desvelábase por entenderlas, y desentrañarles el sentido, que no se lo sacara, ni las entendiera el mismo Aristóteles, si resucitara para sólo ello. No estaba muy bien con las heridas que don Belianís daba y recibía, porque se imaginaba que por grandes maestros que le hubiesen curado, no dejaría de tener el rostro y todo el cuerpo lleno de cicatrices y señales; pero con todo alababa en su autor aquel acabar su libro con la promesa de aquella inacabable aventura, y muchas veces le vino deseo de tomar la pluma, y darle fin al pie de la letra como allí se promete; y sin duda alguna lo hiciera, y aun saliera con ello, si otros mayores y continuos pensamientos no se lo estorbaran. En resolución, él se enfrascó tanto en su lectura, que se le pasaban las noches leyendo de claro en claro, y los días de turbio en turbio, y así, del poco dormir y del mucho leer, se le secó el cerebro, de manera que vino a perder el juicio. Llenósele la fantasía de todo aquello que leía en los libros, así de encantamientos, como de pendencias, batallas, desafíos, heridas, requiebros, amores, tormentas y disparates imposibles, y asentósele de tal modo en la imaginación que era verdad toda aquella máquina de aquellas soñadas invenciones que leía, que para él no había otra historia más cierta en el mundo. Que trata de la primera salida que de su tierra hizo el ingenioso Don Quijote Hechas, pues, estas prevenciones, no quiso aguardar más tiempo a poner en efeto su pensamiento, apretándole a ello la falta que él pensaba que hacía en el mundo su tardanza, según eran los agravios que pensaba deshacer, tuertos que enderezar, sinrazones que emendar y abusos que mejorar y deudas que satisfacer. Y así, sin dar parte a persona alguna de su intención y sin que nadie le viese, una mañana, antes del día, que era uno de los calurosos del mes de Julio, se armó de todas sus armas, subió sobre Rocinante, puesta su mal compuesta celada, embrazó su adarga, tomó su lanza y por la puerta falsa de un corral salió al campo con grandísimo contento y alborozo de ver con cuánta facilidad había dado principio a su buen deseo. Yendo, pues, caminando nuestro flamante aventurero, iba hablando consigo mesmo, y diciendo: —¿Quién duda, sino que en los venideros tiempos, cuando salga a luz la verdadera historia de mis famosos hechos, que el sabio que los escribiere no ponga, cuando llegue a contar esta mi primera salida tan de mañana, desta manera?: Apenas había el rubicundo Apolo tendido por la faz de la ancha y espaciosa tierra las doradas hebras de sus hermosos cabellos, y apenas los pequeños y pintados pajarillos con sus arpadas lenguas habían saludado con dulce y meliflua armonía la venida de la rosada Aurora, que, dejando la blanda cama del celoso marido, por las puertas y balcones del manchego horizonte a los mortales se mostraba, cuando el famoso caballero don Quijote de la Mancha, dejando las ociosas plumas, subió sobre su famoso caballo Rocinante y comenzó a caminar por el antiguo y conocido Campo de Montiel. Casi todo aquel día caminó sin acontecerle cosa que de contar fuese, de lo cual se desesperaba, porque quisiera topar luego luego con quien hacer experiencia del valor de su fuerte brazo. Autores hay que dicen que la primera aventura que le avino fue la del Puerto Lápice, otros dicen que la de los molinos de viento; pero lo que yo he podido averiguar en este caso, y lo que he hallado escrito en los anales de la Mancha, es que él anduvo todo aquel día, y, al anochecer, su rocín y él se hallaron cansados y muertos de hambre, y que, mirando a todas partes por ver si descubriría algún castillo o alguna majada de pastores donde recogerse y adonde pudiese remediar su mucha hambre y necesidad, vio, no lejos del camino por donde iba, una venta, que fue como si viera una estrella que, no a los portales, sino a los alcázares de su redención le encaminaba. Diose priesa a caminar, y llegó a ella a tiempo que anochecía. ( `${pageNumber} / ${totalPages}` )} fixed />
); Font.register({ family: 'Oswald', src: 'https://fonts.gstatic.com/s/oswald/v13/Y_TKV6o8WovbUd3m_X9aAA.ttf' }); const styles = StyleSheet.create({ titleBlock: { alignItems: 'center', marginBottom: 8, }, title: { fontSize: 24, fontFamily: 'Oswald', textAlign: 'center', color: '#2c1810', letterSpacing: 2, textTransform: 'uppercase', }, hr: { borderBottomWidth: 1, borderBottomColor: '#8B4513', width: 60, marginVertical: 16, alignSelf: 'center', }, author: { fontSize: 13, textAlign: 'center', color: '#8B4513', fontFamily: 'Times-Roman', fontStyle: 'italic', }, body: { paddingTop: 50, paddingBottom: 65, paddingHorizontal: 65, }, header: { fontSize: 8, marginBottom: 24, textAlign: 'center', color: '#999', letterSpacing: 3, textTransform: 'uppercase', }, chapterHeading: { alignItems: 'center', marginBottom: 20, paddingTop: 20, }, chapterNumber: { fontSize: 36, fontFamily: 'Oswald', color: '#8B4513', marginBottom: 8, }, chapterRule: { borderBottomWidth: 0.5, borderBottomColor: '#8B4513', width: 40, marginVertical: 8, }, chapterTitle: { fontSize: 14, fontFamily: 'Times-Roman', fontStyle: 'italic', textAlign: 'center', color: '#555', maxWidth: 320, lineHeight: 1.6, }, text: { marginBottom: 10, fontSize: 11, textAlign: 'justify', fontFamily: 'Times-Roman', lineHeight: 1.7, color: '#333', }, pullQuote: { marginVertical: 16, marginHorizontal: 30, paddingLeft: 16, borderLeftWidth: 2, borderLeftColor: '#8B4513', }, pullQuoteText: { fontSize: 12, fontFamily: 'Times-Roman', fontStyle: 'italic', lineHeight: 1.7, color: '#555', }, chapterImage: { marginVertical: 16, marginHorizontal: 60, }, pageNumber: { position: 'absolute', fontSize: 9, bottom: 30, left: 0, right: 0, textAlign: 'center', color: '#999', }, }); ReactPDF.render(); ================================================ FILE: examples/path.txt ================================================ const styles = StyleSheet.create({ page: { padding: 60 }, }); const doc = ( ); ReactPDF.render(doc); ================================================ FILE: examples/picker-formlist.txt ================================================ const Combos = () => { // Static List of names from https://restcountries.com const countries = ["Afghanistan", "Albania", "Algeria", "American Samoa", "Andorra", "Angola", "Anguilla", "Antarctica", "Antigua and Barbuda", "Argentina", "Armenia", "Aruba", "Australia", "Austria", "Azerbaijan", "Bahamas", "Bahrain", "Bangladesh", "Barbados", "Belarus", "Belgium", "Belize", "Benin", "Bermuda", "Bhutan", "Bolivia", "Bosnia and Herzegovina", "Botswana", "Bouvet Island", "Brazil", "British Indian Ocean Territory", "British Virgin Islands", "Brunei", "Bulgaria", "Burkina Faso", "Burundi", "Cambodia", "Cameroon", "Canada", "Cape Verde", "Caribbean Netherlands", "Cayman Islands", "Central African Republic", "Chad", "Chile", "China", "Christmas Island", "Cocos (Keeling) Islands", "Colombia", "Comoros", "Cook Islands", "Costa Rica", "Croatia", "Cuba", "Curaçao", "Cyprus", "Czechia", "DR Congo", "Denmark", "Djibouti", "Dominica", "Dominican Republic", "Ecuador", "Egypt", "El Salvador", "Equatorial Guinea", "Eritrea", "Estonia", "Eswatini", "Ethiopia", "Falkland Islands", "Faroe Islands", "Fiji", "Finland", "France", "French Guiana", "French Polynesia", "French Southern and Antarctic Lands", "Gabon", "Gambia", "Georgia", "Germany", "Ghana", "Gibraltar", "Greece", "Greenland", "Grenada", "Guadeloupe", "Guam", "Guatemala", "Guernsey", "Guinea", "Guinea-Bissau", "Guyana", "Haiti", "Heard Island and McDonald Islands", "Honduras", "Hong Kong", "Hungary", "Iceland", "India", "Indonesia", "Iran", "Iraq", "Ireland", "Isle of Man", "Israel", "Italy", "Ivory Coast", "Jamaica", "Japan", "Jersey", "Jordan", "Kazakhstan", "Kenya", "Kiribati", "Kosovo", "Kuwait", "Kyrgyzstan", "Laos", "Latvia", "Lebanon", "Lesotho", "Liberia", "Libya", "Liechtenstein", "Lithuania", "Luxembourg", "Macau", "Madagascar", "Malawi", "Malaysia", "Maldives", "Mali", "Malta", "Marshall Islands", "Martinique", "Mauritania", "Mauritius", "Mayotte", "Mexico", "Micronesia", "Moldova", "Monaco", "Mongolia", "Montenegro", "Montserrat", "Morocco", "Mozambique", "Myanmar", "Namibia", "Nauru", "Nepal", "Netherlands", "New Caledonia", "New Zealand", "Nicaragua", "Niger", "Nigeria", "Niue", "Norfolk Island", "North Korea", "North Macedonia", "Northern Mariana Islands", "Norway", "Oman", "Pakistan", "Palau", "Palestine", "Panama", "Papua New Guinea", "Paraguay", "Peru", "Philippines", "Pitcairn Islands", "Poland", "Portugal", "Puerto Rico", "Qatar", "Republic of the Congo", "Romania", "Russia", "Rwanda", "Réunion", "Saint Barthélemy", "Saint Helena, Ascension and Tristan da Cunha", "Saint Kitts and Nevis", "Saint Lucia", "Saint Martin", "Saint Pierre and Miquelon", "Saint Vincent and the Grenadines", "Samoa", "San Marino", "Saudi Arabia", "Senegal", "Serbia", "Seychelles", "Sierra Leone", "Singapore", "Sint Maarten", "Slovakia", "Slovenia", "Solomon Islands", "Somalia", "South Africa", "South Georgia", "South Korea", "South Sudan", "Spain", "Sri Lanka", "Sudan", "Suriname", "Svalbard and Jan Mayen", "Sweden", "Switzerland", "Syria", "São Tomé and Príncipe", "Taiwan", "Tajikistan", "Tanzania", "Thailand", "Timor-Leste", "Togo", "Tokelau", "Tonga", "Trinidad and Tobago", "Tunisia", "Turkey", "Turkmenistan", "Turks and Caicos Islands", "Tuvalu", "Uganda", "Ukraine", "United Arab Emirates", "United Kingdom", "United States", "United States Minor Outlying Islands", "United States Virgin Islands", "Uruguay", "Uzbekistan", "Vanuatu", "Vatican City", "Venezuela", "Vietnam", "Wallis and Futuna", "Western Sahara", "Yemen", "Zambia", "Zimbabwe"]; return ( Country-Picker: Country-FormList: ) }; const styles = StyleSheet.create({ page: { padding: 60 }, picker: { height: '20px' }, formlist: { height: '100px' }, break: { marginBottom: 10 } }); const doc = ( ); ReactPDF.render(doc); ================================================ FILE: examples/polygon.txt ================================================ const styles = StyleSheet.create({ page: { padding: 60 }, }); const doc = ( ); ReactPDF.render(doc); ================================================ FILE: examples/polyline.txt ================================================ const styles = StyleSheet.create({ page: { padding: 60 }, }); const doc = ( ); ReactPDF.render(doc); ================================================ FILE: examples/quick-start.txt ================================================ // import React from 'react'; // import { Page, Text, View, Document, 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 = () => ( Section #1 Section #2 ); ReactPDF.render(); ================================================ FILE: examples/radialgradient.txt ================================================ const styles = StyleSheet.create({ page: { padding: 60 }, }); const doc = ( ); ReactPDF.render(doc); ================================================ FILE: examples/rect.txt ================================================ const styles = StyleSheet.create({ page: { padding: 60 }, }); const doc = ( ); ReactPDF.render(doc); ================================================ FILE: examples/resume.txt ================================================ const styles = StyleSheet.create({ container: { flexDirection: 'row', '@media max-width: 400': { flexDirection: 'column', }, }, image: { marginBottom: 10, '@media max-width: 400': { width: 290, }, }, title: { fontSize: 14, marginBottom: 10, textTransform: 'uppercase', }, leftColumn: { flexDirection: 'column', width: 170, marginLeft: 30, marginRight: 15, marginTop: 20, '@media max-width: 400': { width: 290, marginRight: 30, }, '@media orientation: landscape': { width: 200, marginRight: 50, }, }, rightColumn: { flexDirection: 'column', flexGrow: 1, marginLeft: 15, marginRight: 30, marginTop: 20, '@media max-width: 400': { marginTop: 10, marginLeft: 30, }, }, footer: { fontSize: 12, textAlign: 'center', marginTop: 25, marginHorizontal: 30, paddingVertical: 10, borderWidth: 3, borderColor: 'gray', borderStyle: 'dashed', '@media orientation: landscape': { marginTop: 10, }, }, item: { flexDirection: 'row', marginBottom: 5, }, itemLeftColumn: { flexDirection: 'column', marginRight: 10, }, itemRightColumn: { flexDirection: 'column', flexGrow: 9, }, bulletPoint: { fontSize: 10, }, itemContent: { fontSize: 10, fontFamily: 'Lato', }, headerContainer: { flexDirection: 'row', marginTop: 30, marginLeft: 30, marginRight: 30, marginBottom: 0, borderBottomWidth: 2, borderBottomColor: '#112131', borderBottomStyle: 'solid', alignItems: 'stretch', }, detailColumn: { flexDirection: 'column', flexGrow: 9, }, linkColumn: { flexDirection: 'column', flexGrow: 2, alignSelf: 'flex-end', justifySelf: 'flex-end', }, name: { fontSize: 24, textTransform: 'uppercase', }, subtitle: { fontSize: 10, justifySelf: 'flex-end', textTransform: 'uppercase', }, link: { fontSize: 10, color: 'black', textDecoration: 'none', alignSelf: 'flex-end', justifySelf: 'flex-end', }, educationContainer: { marginBottom: 10, }, school: { fontSize: 10, }, degree: { fontSize: 10, }, candidate: { fontSize: 10, }, skillTitle: { fontSize: 11, marginBottom: 10, }, skills: { fontSize: 10, marginBottom: 10, }, experienceContainer: { marginBottom: 10, }, date: { fontSize: 11, }, detailContainer: { flexDirection: 'row', }, detailLeftColumn: { flexDirection: 'column', marginLeft: 10, marginRight: 10, }, detailRightColumn: { flexDirection: 'column', flexGrow: 9, }, bulletPoint: { fontSize: 10, }, details: { fontSize: 10, }, headerContainer: { flexDirection: 'row', }, experienceLeftColumn: { flexDirection: 'column', flexGrow: 9, }, experienceRightColumn: { flexDirection: 'column', flexGrow: 1, alignItems: 'flex-end', justifySelf: 'flex-end', }, experienceTitle: { fontSize: 11, color: 'black', textDecoration: 'none', }, }); const Header = () => ( Luke Skywalker Jedi Master luke@theforce.com ); const Title = ({ children }) => {children}; const List = ({ children }) => children; const Item = ({ children }) => ( {children} ); const Education = () => ( Education Jedi Academy Jedi Master A long, long time ago ); const SkillEntry = ({ name, skills }) => ( {name} {skills.map((skill, i) => {skill})} ); const Skills = () => ( Skills ); const ExperienceEntry = ({ company, details, position, date }) => { const title = `${company} | ${position}`; return ( {title} {date} {details.map((detail, i) => ( {detail} ))} ); }; const Experience = () => ( Experience ); const resume = (
This IS the candidate you are looking for ); ReactPDF.render(resume); ================================================ FILE: examples/styles.txt ================================================ const styles = StyleSheet.create({ page: { backgroundColor: 'tomato' }, section: { color: 'white', textAlign: 'center', margin: 30 } }); const doc = ( Section #1 ); ReactPDF.render(doc); ================================================ FILE: examples/svg.txt ================================================ const styles = StyleSheet.create({ page: { padding: 60 }, }); const Tiger = () => ( ) const doc = ( ); ReactPDF.render(doc); ================================================ FILE: examples/svgtext.txt ================================================ const styles = StyleSheet.create({ page: { padding: 60 }, }); const doc = ( React-pdf is cool ); ReactPDF.render(doc); ================================================ FILE: examples/text.txt ================================================ const styles = StyleSheet.create({ title: { margin: 20, fontSize: 25, textAlign: 'center', backgroundColor: '#e4e4e4', textDecoration: 'underline', textTransform: 'uppercase', }, body: { flexGrow: 1, }, row: { flexGrow: 1, flexDirection: 'row', }, block: { flexGrow: 1, }, text: { flexGrow: 3, margin: 10, }, fill1: { flexGrow: 2, backgroundColor: '#e14427', }, fill2: { flexGrow: 2, backgroundColor: '#e6672d', }, fill3: { flexGrow: 2, backgroundColor: '#e78632', }, fill4: { flexGrow: 2, backgroundColor: '#e29e37', }, }); const doc = ( Lorem Ipsum Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad 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. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad 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. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad 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. Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad 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. ); ReactPDF.render(doc); ================================================ FILE: examples/textinput.txt ================================================ const UserInformation = () => ( User Information Username Age Region First name Second name Last name Description ); const styles = StyleSheet.create({ page: { padding: 60 }, heading: { fontSize: 24, textAlign: 'center', marginBottom: 40 }, textinput: { height: 14.4, marginRight: 50, marginTop: 10, marginBottom: 20 }, multiline: { height: 72 }, verticalFlex: { display: 'flex', flexDirection: 'row', justifyContent: 'space-around' }, flexGrow: { flexGrow: 1 } }); const doc = ( ); ReactPDF.render(doc); ================================================ FILE: next.config.js ================================================ module.exports = { swcMinify: false, webpack: (config, options) => { config.module.rules.push({ test: /\.md/, use: [options.defaultLoaders.babel, '@mdx-js/loader'], }); config.module.rules.push({ test: /\.worker\.(min\.)?js$/, loader: 'file-loader', options: { name: '[contenthash].[ext]', publicPath: '_next/static/worker', outputPath: 'static/worker', }, }); config.resolve.alias.canvas = false; return config; }, }; ================================================ FILE: next.config_old.js ================================================ module.exports = { webpack: (config, options) => { config.module.rules.push({ test: /\.md/, use: [options.defaultLoaders.babel, '@mdx-js/loader'], }); config.module.rules.push({ test: /\.worker\.js$/, loader: 'worker-loader', // options: { inline: true }, // also works options: { name: '[hash].worker.js', publicPath: '/_next/', }, }); return config; }, }; ================================================ FILE: now.json ================================================ { "name": "@react-pdf/site", "version": 2 } ================================================ FILE: package.json ================================================ { "name": "@react-pdf/site", "version": "1.0.0", "license": "MIT", "private": true, "scripts": { "dev": "next", "build": "next build", "start": "next start", "deploy": "now --public" }, "dependencies": { "@emotion/core": "^10.0.35", "@emotion/styled": "^10.0.27", "@fortawesome/fontawesome-svg-core": "^1.2.35", "@fortawesome/free-brands-svg-icons": "^5.15.3", "@fortawesome/free-solid-svg-icons": "^5.15.3", "@fortawesome/react-fontawesome": "^0.1.14", "@mdx-js/loader": "^1.5.1", "@next/mdx": "^9.1.1", "@react-pdf/math": "^1.0.1", "@react-pdf/renderer": "^4.4.0", "@vercel/analytics": "^1.1.1", "add": "^2.0.6", "buble": "^0.19.3", "codemirror": "^5.45.0", "date-fns": "^2.19.0", "dotenv": "^6.0.0", "emotion": "^10.0.27", "emotion-server": "^10.0.27", "emotion-theming": "^10.0.27", "extract-text-webpack-plugin": "^4.0.0-beta.0", "lodash.debounce": "^4.0.8", "lz-string": "^1.4.4", "next": "^14.2.15", "prismjs": "^1.30.0", "prop-types": "^15.6.2", "react": "^18.2.0", "react-copy-to-clipboard": "^5.0.1", "react-dom": "^18.2.0", "react-ga": "^2.5.3", "react-pdf": "^9.2.1", "react-prism": "^4.3.2", "react-tippy": "^1.2.2", "react-use": "^15.3.4", "recompose": "^0.30.0", "worker-loader": "^3.0.1" }, "devDependencies": { "babel-plugin-prismjs": "^1.0.2", "babel-plugin-transform-define": "^1.3.0", "raw-loader": "^0.5.1" }, "packageManager": "yarn@1.22.22+sha512.a6b2f7906b721bba3d67d4aff083df04dad64c399707841b7acf00f6b133b7ac24255f2652fa22ae3534329dc6180534e98d17432037ff6fd140556e2bb3137e" } ================================================ FILE: pages/_app.js ================================================ import React from 'react'; import { MDXProvider } from '@mdx-js/react'; import { Analytics } from '@vercel/analytics/react'; import { ThemeProvider } from 'emotion-theming'; import Head from 'next/head'; import theme from '../src/styled/theme'; import components from '../src/lib/markdown'; // Global styles require('react-tippy/dist/tippy.css'); require('react-pdf/dist/Page/AnnotationLayer.css'); require('react-pdf/dist/Page/TextLayer.css'); require('../public/styles/index.css'); require('../public/styles/fonts.css'); require('../public/styles/prism.css'); require('../public/styles/tooltips.css'); require('../public/styles/codemirror.css'); import App from 'next/app'; class MyApp extends App { render() { const { Component, pageProps, router } = this.props; return ( <> React-pdf ); } } export default MyApp; ================================================ FILE: pages/_document.js ================================================ import { extractCritical } from 'emotion-server' import Document, { Html, Head, Main, NextScript } from 'next/document'; class MyDocument extends Document { static async getInitialProps(ctx) { const initialProps = await Document.getInitialProps(ctx) const styles = extractCritical(initialProps.html) return { ...initialProps, styles: ( <> {initialProps.styles}