Giter Club home page Giter Club logo

react-pdf's Introduction

npm downloads CI

React-PDF

Display PDFs in your React app as easily as if they were images.

Lost?

This package is used to display existing PDFs. If you wish to create PDFs using React, you may be looking for @react-pdf/renderer.

tl;dr

  • Install by executing npm install react-pdf or yarn add react-pdf.
  • Import by adding import { Document } from 'react-pdf'.
  • Use by adding <Document file="..." />. file can be a URL, base64 content, Uint8Array, and more.
  • Put <Page /> components inside <Document /> to render pages.

Demo

A minimal demo page can be found in sample directory.

Online demo is also available!

Before you continue

React-PDF is under constant development. This documentation is written for React-PDF 9.x branch. If you want to see documentation for other versions of React-PDF, use dropdown on top of GitHub page to switch to an appropriate tag. Here are quick links to the newest docs from each branch:

Getting started

Compatibility

Browser support

React-PDF supports all modern browsers. It is tested with the latest versions of Chrome, Edge, Safari, Firefox, and Opera.

The following browsers are supported out of the box in React-PDF v9:

  • Chrome ≥119
  • Edge ≥119
  • Safari ≥17.4
  • Firefox ≥121

You may extend the list of supported browsers by providing additional polyfills (e.g. for Array.prototype.at, Promise.allSettled or Promise.withResolvers) and either configuring your bundler to transpile pdfjs-dist or using legacy PDF.js worker.

If you need to support older browsers, you will need to use React-PDF v6 or earlier.

React

To use the latest version of React-PDF, your project needs to use React 16.8 or later.

If you use an older version of React, please refer to the table below to a find suitable React-PDF version.

React version Newest compatible React-PDF version
≥16.8 latest
≥16.3 5.x
≥15.5 4.x

Preact

React-PDF may be used with Preact.

Installation

Add React-PDF to your project by executing npm install react-pdf or yarn add react-pdf.

Next.js

If you use Next.js without Turbopack enabled, add the following to your next.config.js:

module.exports = {
+ webpack: (config) => {
+   config.resolve.alias.canvas = false;

+   return config;
+ },
}

If you use Next.js with Turbopack enabled, add empty-module.ts file:

export default {};

and add the following to your next.config.js:

module.exports = {
+ experimental: {
+   turbo: {
+     resolveAlias: {
+       canvas: './empty-module.ts',
+     },
+   },
+ },
};

Configure PDF.js worker

For React-PDF to work, PDF.js worker needs to be provided. You have several options.

Import worker (recommended)

For most cases, the following example will work:

import { pdfjs } from 'react-pdf';

pdfjs.GlobalWorkerOptions.workerSrc = new URL(
  'pdfjs-dist/build/pdf.worker.min.mjs',
  import.meta.url,
).toString();

Note

In Next.js:

  • Using App Router, make sure to add 'use client'; to the top of the file.
  • Using Pages Router, make sure to disable SSR when importing the component you're using this code in.

Note

pnpm requires an .npmrc file with public-hoist-pattern[]=pdfjs-dist for this to work.

See more examples
Parcel 2

For Parcel 2, you need to use a slightly different code:

 pdfjs.GlobalWorkerOptions.workerSrc = new URL(
-  'pdfjs-dist/build/pdf.worker.min.mjs',
+  'npm:pdfjs-dist/build/pdf.worker.min.mjs',
   import.meta.url,
 ).toString();

Copy worker to public directory

You will have to make sure on your own that pdf.worker.mjs file from pdfjs-dist/build is copied to your project's output folder.

For example, you could use a custom script like:

import path from 'node:path';
import fs from 'node:fs';

const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
const pdfWorkerPath = path.join(pdfjsDistPath, 'build', 'pdf.worker.mjs');

fs.cpSync(pdfWorkerPath, './dist/pdf.worker.mjs', { recursive: true });

Use external CDN

import { pdfjs } from 'react-pdf';

pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`;

Legacy PDF.js worker

If you need to support older browsers, you may use legacy PDF.js worker. To do so, follow the instructions above, but replace /build/ with legacy/build/ in PDF.js worker import path, for example:

 pdfjs.GlobalWorkerOptions.workerSrc = new URL(
-  'pdfjs-dist/build/pdf.worker.min.mjs',
+  'pdfjs-dist/legacy/build/pdf.worker.min.mjs',
   import.meta.url,
 ).toString();

or:

-pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/build/pdf.worker.min.mjs`;
+pdfjs.GlobalWorkerOptions.workerSrc = `//unpkg.com/pdfjs-dist@${pdfjs.version}/legacy/build/pdf.worker.min.mjs`;

Usage

Here's an example of basic usage:

import { useState } from 'react';
import { Document, Page } from 'react-pdf';

function MyApp() {
  const [numPages, setNumPages] = useState<number>();
  const [pageNumber, setPageNumber] = useState<number>(1);

  function onDocumentLoadSuccess({ numPages }: { numPages: number }): void {
    setNumPages(numPages);
  }

  return (
    <div>
      <Document file="somefile.pdf" onLoadSuccess={onDocumentLoadSuccess}>
        <Page pageNumber={pageNumber} />
      </Document>
      <p>
        Page {pageNumber} of {numPages}
      </p>
    </div>
  );
}

Check the sample directory in this repository for a full working example. For more examples and more advanced use cases, check Recipes in React-PDF Wiki.

Support for annotations

If you want to use annotations (e.g. links) in PDFs rendered by React-PDF, then you would need to include stylesheet necessary for annotations to be correctly displayed like so:

import 'react-pdf/dist/Page/AnnotationLayer.css';

Support for text layer

If you want to use text layer in PDFs rendered by React-PDF, then you would need to include stylesheet necessary for text layer to be correctly displayed like so:

import 'react-pdf/dist/Page/TextLayer.css';

Support for non-latin characters

If you want to ensure that PDFs with non-latin characters will render perfectly, or you have encountered the following warning:

Warning: The CMap "baseUrl" parameter must be specified, ensure that the "cMapUrl" and "cMapPacked" API parameters are provided.

then you would also need to include cMaps in your build and tell React-PDF where they are.

Copying cMaps

First, you need to copy cMaps from pdfjs-dist (React-PDF's dependency - it should be in your node_modules if you have React-PDF installed). cMaps are located in pdfjs-dist/cmaps.

Vite

Add vite-plugin-static-copy by executing npm install vite-plugin-static-copy --save-dev or yarn add vite-plugin-static-copy --dev and add the following to your Vite config:

+import path from 'node:path';
+import { createRequire } from 'node:module';

-import { defineConfig } from 'vite';
+import { defineConfig, normalizePath } from 'vite';
+import { viteStaticCopy } from 'vite-plugin-static-copy';

+const require = createRequire(import.meta.url);
+
+const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
+const cMapsDir = normalizePath(path.join(pdfjsDistPath, 'cmaps'));

export default defineConfig({
  plugins: [
+   viteStaticCopy({
+     targets: [
+       {
+         src: cMapsDir,
+         dest: '',
+       },
+     ],
+   }),
  ]
});
Webpack

Add copy-webpack-plugin by executing npm install copy-webpack-plugin --save-dev or yarn add copy-webpack-plugin --dev and add the following to your Webpack config:

+import path from 'node:path';
+import CopyWebpackPlugin from 'copy-webpack-plugin';

+const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
+const cMapsDir = path.join(pdfjsDistPath, 'cmaps');

module.exports = {
  plugins: [
+   new CopyWebpackPlugin({
+     patterns: [
+       {
+         from: cMapsDir,
+         to: 'cmaps/'
+       },
+     ],
+   }),
  ],
};
Other tools

If you use other bundlers, you will have to make sure on your own that cMaps are copied to your project's output folder.

For example, you could use a custom script like:

import path from 'node:path';
import fs from 'node:fs';

const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
const cMapsDir = path.join(pdfjsDistPath, 'cmaps');

fs.cpSync(cMapsDir, 'dist/cmaps/', { recursive: true });

Setting up React-PDF

Now that you have cMaps in your build, pass required options to Document component by using options prop, like so:

// Outside of React component
const options = {
  cMapUrl: '/cmaps/',
};

// Inside of React component
<Document options={options} />;

Note

Make sure to define options object outside of your React component, and use useMemo if you can't.

Alternatively, you could use cMaps from external CDN:

// Outside of React component
import { pdfjs } from 'react-pdf';

const options = {
  cMapUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/cmaps/`,
};

// Inside of React component
<Document options={options} />;

Support for standard fonts

If you want to support PDFs using standard fonts (deprecated in PDF 1.5, but still around), ot you have encountered the following warning:

The standard font "baseUrl" parameter must be specified, ensure that the "standardFontDataUrl" API parameter is provided.

then you would also need to include standard fonts in your build and tell React-PDF where they are.

Copying fonts

First, you need to copy standard fonts from pdfjs-dist (React-PDF's dependency - it should be in your node_modules if you have React-PDF installed). Standard fonts are located in pdfjs-dist/standard_fonts.

Vite

Add vite-plugin-static-copy by executing npm install vite-plugin-static-copy --save-dev or yarn add vite-plugin-static-copy --dev and add the following to your Vite config:

+import path from 'node:path';
+import { createRequire } from 'node:module';

-import { defineConfig } from 'vite';
+import { defineConfig, normalizePath } from 'vite';
+import { viteStaticCopy } from 'vite-plugin-static-copy';

+const require = createRequire(import.meta.url);
+const standardFontsDir = normalizePath(
+  path.join(path.dirname(require.resolve('pdfjs-dist/package.json')), 'standard_fonts')
+);

export default defineConfig({
  plugins: [
+   viteStaticCopy({
+     targets: [
+       {
+         src: standardFontsDir,
+         dest: '',
+       },
+     ],
+   }),
  ]
});
Webpack

Add copy-webpack-plugin by executing npm install copy-webpack-plugin --save-dev or yarn add copy-webpack-plugin --dev and add the following to your Webpack config:

+import path from 'node:path';
+import CopyWebpackPlugin from 'copy-webpack-plugin';

+const standardFontsDir = path.join(path.dirname(require.resolve('pdfjs-dist/package.json')), 'standard_fonts');

module.exports = {
  plugins: [
+   new CopyWebpackPlugin({
+     patterns: [
+       {
+         from: standardFontsDir,
+         to: 'standard_fonts/'
+       },
+     ],
+   }),
  ],
};
Other tools

If you use other bundlers, you will have to make sure on your own that standard fonts are copied to your project's output folder.

For example, you could use a custom script like:

import path from 'node:path';
import fs from 'node:fs';

const pdfjsDistPath = path.dirname(require.resolve('pdfjs-dist/package.json'));
const standardFontsDir = path.join(pdfjsDistPath, 'standard_fonts');

fs.cpSync(standardFontsDir, 'dist/standard_fonts/', { recursive: true });

Setting up React-PDF

Now that you have standard fonts in your build, pass required options to Document component by using options prop, like so:

// Outside of React component
const options = {
  standardFontDataUrl: '/standard_fonts/',
};

// Inside of React component
<Document options={options} />;

Note

Make sure to define options object outside of your React component, and use useMemo if you can't.

Alternatively, you could use standard fonts from external CDN:

// Outside of React component
import { pdfjs } from 'react-pdf';

const options = {
  standardFontDataUrl: `https://unpkg.com/pdfjs-dist@${pdfjs.version}/standard_fonts`,
};

// Inside of React component
<Document options={options} />;

User guide

Document

Loads a document passed using file prop.

Props

Prop name Description Default value Example values
className Class name(s) that will be added to rendered element along with the default react-pdf__Document. n/a
  • String:
    "custom-class-name-1 custom-class-name-2"
  • Array of strings:
    ["custom-class-name-1", "custom-class-name-2"]
error What the component should display in case of an error. "Failed to load PDF file."
  • String:
    "An error occurred!"
  • React element:
    <p>An error occurred!</p>
  • Function:
    this.renderError
externalLinkRel Link rel for links rendered in annotations. "noopener noreferrer nofollow" One of valid values for rel attribute.
  • "noopener"
  • "noreferrer"
  • "nofollow"
  • "noopener noreferrer"
externalLinkTarget Link target for external links rendered in annotations. unset, which means that default behavior will be used One of valid values for target attribute.
  • "_self"
  • "_blank"
  • "_parent"
  • "_top"
file What PDF should be displayed.
Its value can be an URL, a file (imported using import … from … or from file input form element), or an object with parameters (url - URL; data - data, preferably Uint8Array; range - PDFDataRangeTransport.
Warning: Since equality check (===) is used to determine if file object has changed, it must be memoized by setting it in component's state, useMemo or other similar technique.
n/a
  • URL:
    "https://example.com/sample.pdf"
  • File:
    import importedPdf from '../static/sample.pdf' and then
    sample
  • Parameter object:
    { url: 'https://example.com/sample.pdf' }
imageResourcesPath The path used to prefix the src attributes of annotation SVGs. n/a (pdf.js will fallback to an empty string) "/public/images/"
inputRef A prop that behaves like ref, but it's passed to main <div> rendered by <Document> component. n/a
  • Function:
    (ref) => { this.myDocument = ref; }
  • Ref created using createRef:
    this.ref = createRef();

    inputRef={this.ref}
  • Ref created using useRef:
    const ref = useRef();

    inputRef={ref}
loading What the component should display while loading. "Loading PDF…"
  • String:
    "Please wait!"
  • React element:
    <p>Please wait!</p>
  • Function:
    this.renderLoader
noData What the component should display in case of no data. "No PDF file specified."
  • String:
    "Please select a file."
  • React element:
    <p>Please select a file.</p>
  • Function:
    this.renderNoData
onItemClick Function called when an outline item or a thumbnail has been clicked. Usually, you would like to use this callback to move the user wherever they requested to. n/a ({ dest, pageIndex, pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')
onLoadError Function called in case of an error while loading a document. n/a (error) => alert('Error while loading document! ' + error.message)
onLoadProgress Function called, potentially multiple times, as the loading progresses. n/a ({ loaded, total }) => alert('Loading a document: ' + (loaded / total) * 100 + '%')
onLoadSuccess Function called when the document is successfully loaded. n/a (pdf) => alert('Loaded a file with ' + pdf.numPages + ' pages!')
onPassword Function called when a password-protected PDF is loaded. Function that prompts the user for password. (callback) => callback('s3cr3t_p4ssw0rd')
onSourceError Function called in case of an error while retrieving document source from file prop. n/a (error) => alert('Error while retrieving document source! ' + error.message)
onSourceSuccess Function called when document source is successfully retrieved from file prop. n/a () => alert('Document source retrieved!')
options An object in which additional parameters to be passed to PDF.js can be defined. Most notably:
  • cMapUrl;
  • httpHeaders - custom request headers, e.g. for authorization);
  • withCredentials - a boolean to indicate whether or not to include cookies in the request (defaults to false)
For a full list of possible parameters, check PDF.js documentation on DocumentInitParameters.

Note: Make sure to define options object outside of your React component, and use useMemo if you can't.
n/a { cMapUrl: '/cmaps/' }
renderMode Rendering mode of the document. Can be "canvas", "custom" or "none". If set to "custom", customRenderer must also be provided. "canvas" "custom"
rotate Rotation of the document in degrees. If provided, will change rotation globally, even for the pages which were given rotate prop of their own. 90 = rotated to the right, 180 = upside down, 270 = rotated to the left. n/a 90

Page

Displays a page. Should be placed inside <Document />. Alternatively, it can have pdf prop passed, which can be obtained from <Document />'s onLoadSuccess callback function, however some advanced functions like rendering annotations and linking between pages inside a document may not be working correctly.

Props

Prop name Description Default value Example values
canvasBackground Canvas background color. Any valid canvas.fillStyle can be used. n/a "transparent"
canvasRef A prop that behaves like ref, but it's passed to <canvas> rendered by <Canvas> component. n/a
  • Function:
    (ref) => { this.myCanvas = ref; }
  • Ref created using createRef:
    this.ref = createRef();

    inputRef={this.ref}
  • Ref created using useRef:
    const ref = useRef();

    inputRef={ref}
className Class name(s) that will be added to rendered element along with the default react-pdf__Page. n/a
  • String:
    "custom-class-name-1 custom-class-name-2"
  • Array of strings:
    ["custom-class-name-1", "custom-class-name-2"]
customRenderer Function that customizes how a page is rendered. You must set renderMode to "custom" to use this prop. n/a MyCustomRenderer
customTextRenderer Function that customizes how a text layer is rendered. n/a ({ str, itemIndex }) => str.replace(/ipsum/g, value => `<mark>${value}</mark>`)
devicePixelRatio The ratio between physical pixels and device-independent pixels (DIPs) on the current device. window.devicePixelRatio 1
error What the component should display in case of an error. "Failed to load the page."
  • String:
    "An error occurred!"
  • React element:
    <p>An error occurred!</p>
  • Function:
    this.renderError
height Page height. If neither height nor width are defined, page will be rendered at the size defined in PDF. If you define width and height at the same time, height will be ignored. If you define height and scale at the same time, the height will be multiplied by a given factor. Page's default height 300
imageResourcesPath The path used to prefix the src attributes of annotation SVGs. n/a (pdf.js will fallback to an empty string) "/public/images/"
inputRef A prop that behaves like ref, but it's passed to main <div> rendered by <Page> component. n/a
  • Function:
    (ref) => { this.myPage = ref; }
  • Ref created using createRef:
    this.ref = createRef();

    inputRef={this.ref}
  • Ref created using useRef:
    const ref = useRef();

    inputRef={ref}
loading What the component should display while loading. "Loading page…"
  • String:
    "Please wait!"
  • React element:
    <p>Please wait!</p>
  • Function:
    this.renderLoader
noData What the component should display in case of no data. "No page specified."
  • String:
    "Please select a page."
  • React element:
    <p>Please select a page.</p>
  • Function:
    this.renderNoData
onGetAnnotationsError Function called in case of an error while loading annotations. n/a (error) => alert('Error while loading annotations! ' + error.message)
onGetAnnotationsSuccess Function called when annotations are successfully loaded. n/a (annotations) => alert('Now displaying ' + annotations.length + ' annotations!')
onGetStructTreeError Function called in case of an error while loading structure tree. n/a (error) => alert('Error while loading structure tree! ' + error.message)
onGetStructTreeSuccess Function called when structure tree is successfully loaded. n/a (structTree) => alert(JSON.stringify(structTree))
onGetTextError Function called in case of an error while loading text layer items. n/a (error) => alert('Error while loading text layer items! ' + error.message)
onGetTextSuccess Function called when text layer items are successfully loaded. n/a ({ items, styles }) => alert('Now displaying ' + items.length + ' text layer items!')
onLoadError Function called in case of an error while loading the page. n/a (error) => alert('Error while loading page! ' + error.message)
onLoadSuccess Function called when the page is successfully loaded. n/a (page) => alert('Now displaying a page number ' + page.pageNumber + '!')
onRenderAnnotationLayerError Function called in case of an error while rendering the annotation layer. n/a (error) => alert('Error while loading annotation layer! ' + error.message)
onRenderAnnotationLayerSuccess Function called when annotations are successfully rendered on the screen. n/a () => alert('Rendered the annotation layer!')
onRenderError Function called in case of an error while rendering the page. n/a (error) => alert('Error while loading page! ' + error.message)
onRenderSuccess Function called when the page is successfully rendered on the screen. n/a () => alert('Rendered the page!')
onRenderTextLayerError Function called in case of an error while rendering the text layer. n/a (error) => alert('Error while rendering text layer! ' + error.message)
onRenderTextLayerSuccess Function called when the text layer is successfully rendered on the screen. n/a () => alert('Rendered the text layer!')
pageIndex Which page from PDF file should be displayed, by page index. Ignored if pageNumber prop is provided. 0 1
pageNumber Which page from PDF file should be displayed, by page number. If provided, pageIndex prop will be ignored. 1 2
pdf pdf object obtained from <Document />'s onLoadSuccess callback function. (automatically obtained from parent <Document />) pdf
renderAnnotationLayer Whether annotations (e.g. links) should be rendered. true false
renderForms Whether forms should be rendered. renderAnnotationLayer prop must be set to true. false true
renderMode Rendering mode of the document. Can be "canvas", "custom" or "none". If set to "custom", customRenderer must also be provided. "canvas" "custom"
renderTextLayer Whether a text layer should be rendered. true false
rotate Rotation of the page in degrees. 90 = rotated to the right, 180 = upside down, 270 = rotated to the left. Page's default setting, usually 0 90
scale Page scale. 1 0.5
width Page width. If neither height nor width are defined, page will be rendered at the size defined in PDF. If you define width and height at the same time, height will be ignored. If you define width and scale at the same time, the width will be multiplied by a given factor. Page's default width 300

Outline

Displays an outline (table of contents). Should be placed inside <Document />. Alternatively, it can have pdf prop passed, which can be obtained from <Document />'s onLoadSuccess callback function.

Props

Prop name Description Default value Example values
className Class name(s) that will be added to rendered element along with the default react-pdf__Outline. n/a
  • String:
    "custom-class-name-1 custom-class-name-2"
  • Array of strings:
    ["custom-class-name-1", "custom-class-name-2"]
inputRef A prop that behaves like ref, but it's passed to main <div> rendered by <Outline> component. n/a
  • Function:
    (ref) => { this.myOutline = ref; }
  • Ref created using createRef:
    this.ref = createRef();

    inputRef={this.ref}
  • Ref created using useRef:
    const ref = useRef();

    inputRef={ref}
onItemClick Function called when an outline item has been clicked. Usually, you would like to use this callback to move the user wherever they requested to. n/a ({ dest, pageIndex, pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')
onLoadError Function called in case of an error while retrieving the outline. n/a (error) => alert('Error while retrieving the outline! ' + error.message)
onLoadSuccess Function called when the outline is successfully retrieved. n/a (outline) => alert('The outline has been successfully retrieved.')

Thumbnail

Displays a thumbnail of a page. Does not render the annotation layer or the text layer. Does not register itself as a link target, so the user will not be scrolled to a Thumbnail component when clicked on an internal link (e.g. in Table of Contents). When clicked, attempts to navigate to the page clicked (similarly to a link in Outline). Should be placed inside <Document />. Alternatively, it can have pdf prop passed, which can be obtained from <Document />'s onLoadSuccess callback function.

Props

Props are the same as in <Page /> component, but certain annotation layer and text layer-related props are not available:

  • customTextRenderer
  • onGetAnnotationsError
  • onGetAnnotationsSuccess
  • onGetTextError
  • onGetTextSuccess
  • onRenderAnnotationLayerError
  • onRenderAnnotationLayerSuccess
  • onRenderTextLayerError
  • onRenderTextLayerSuccess
  • renderAnnotationLayer
  • renderForms
  • renderTextLayer

On top of that, additional props are available:

Prop name Description Default value Example values
className Class name(s) that will be added to rendered element along with the default react-pdf__Thumbnail. n/a
  • String:
    "custom-class-name-1 custom-class-name-2"
  • Array of strings:
    ["custom-class-name-1", "custom-class-name-2"]
onItemClick Function called when a thumbnail has been clicked. Usually, you would like to use this callback to move the user wherever they requested to. n/a ({ dest, pageIndex, pageNumber }) => alert('Clicked an item from page ' + pageNumber + '!')

Useful links

License

The MIT License.

Author

Wojciech Maj Wojciech Maj

Thank you

This project wouldn't be possible without the awesome work of Niklas Närhinen who created its original version and without Mozilla, author of pdf.js. Thank you!

Sponsors

Thank you to all our sponsors! Become a sponsor and get your image on our README on GitHub.

Backers

Thank you to all our backers! Become a backer and get your image on our README on GitHub.

Top Contributors

Thank you to all our contributors that helped on this project!

Top Contributors

react-pdf's People

Contributors

bartvanhoutte-ading avatar danielruf avatar dependabot[bot] avatar flacerdk avatar gwenaelp avatar iamtommcc avatar indigolain avatar jeetiss avatar jkhoang313 avatar juliakieserman avatar kerumen avatar loklaan avatar majkiw avatar mattl75 avatar migrachev avatar mochamadsatria avatar nnarhinen avatar olef avatar oze4 avatar paescuj avatar phatcatmatt avatar pstevovski avatar robsco-git avatar rsylvian avatar saadq avatar stefanw avatar sunnylqm avatar suyesh avatar tonycosentini avatar wojtekmaj avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

react-pdf's Issues

ReactPDF won't pass the test

The new version is working perfectly in the project, but it does not pass the test for me.
here are versions:

"babel-jest": "^20.0.3",
"jest": "20.1.0-alpha.3",
"react-pdf": "^1.8.3",

here is the test code.
P.S: PDFViewer has the ReactPDF inside.

import React from 'react';
import ReactDOM from 'react-dom';
import PDFViewer from './index';
import { wrapInMuiThemeProvider } from '../../util';
import injectTapEventPlugin from 'react-tap-event-plugin';

injectTapEventPlugin();

it('renders without crashing', () => {
  const div = document.createElement('div');
  const elem = (<PDFViewer file={'https://rawgit.com/nnarhinen/react-pdf/master/sample/sample.pdf'} />);
  ReactDOM.render(wrapInMuiThemeProvider(elem), div);
});

and here is the complete result:

No PDFJS.workerSrc specified

      at getWorkerSrc (node_modules/pdfjs-dist/build/pdf.js:2494:11)
      at loader (node_modules/pdfjs-dist/build/pdf.js:2504:29)
      at setupFakeWorkerGlobal (node_modules/pdfjs-dist/build/pdf.js:2508:5)
      at Object.PDFWorker_setupFakeWorker [as _setupFakeWorker] (node_modules/pdfjs-dist/build/pdf.js:2644:7)
      at Object.PDFWorker_initialize [as _initialize] (node_modules/pdfjs-dist/build/pdf.js:2635:12)
      at Object.PDFWorker (node_modules/pdfjs-dist/build/pdf.js:2532:10)
      at Object.getDocument (node_modules/pdfjs-dist/build/pdf.js:1923:60)
      at ReactPDF.loadDocument (node_modules/react-pdf/build/react-pdf.js:196:36)
      at ReactPDF.handleFileLoad (node_modules/react-pdf/build/react-pdf.js:140:23)
      at ReactPDF.componentDidMount (node_modules/react-pdf/build/react-pdf.js:43:12)
      at node_modules/react-dom/lib/ReactCompositeComponent.js:265:25
      at measureLifeCyclePerf (node_modules/react-dom/lib/ReactCompositeComponent.js:75:12)
      at node_modules/react-dom/lib/ReactCompositeComponent.js:264:11
      at CallbackQueue.notifyAll (node_modules/react-dom/lib/CallbackQueue.js:76:22)
      at ReactReconcileTransaction.close (node_modules/react-dom/lib/ReactReconcileTransaction.js:80:26)
      at ReactReconcileTransaction.closeAll (node_modules/react-dom/lib/Transaction.js:206:25)
      at ReactReconcileTransaction.perform (node_modules/react-dom/lib/Transaction.js:153:16)
      at batchedMountComponentIntoNode (node_modules/react-dom/lib/ReactMount.js:126:15)
      at ReactDefaultBatchingStrategyTransaction.perform (node_modules/react-dom/lib/Transaction.js:140:20)
      at Object.batchedUpdates (node_modules/react-dom/lib/ReactDefaultBatchingStrategy.js:62:26)
      at Object.batchedUpdates (node_modules/react-dom/lib/ReactUpdates.js:97:27)
      at Object._renderNewRootComponent (node_modules/react-dom/lib/ReactMount.js:320:18)
      at Object._renderSubtreeIntoContainer (node_modules/react-dom/lib/ReactMount.js:401:32)
      at Object.render (node_modules/react-dom/lib/ReactMount.js:422:23)
      at Object.<anonymous>.it (src/RegLib/PDFViewer/PDFViewer.test.js:12:48)
      at process._tickCallback (internal/process/next_tick.js:103:7)

Is it a bug or a problem of mine?
Thanks.

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined

I am trying to implement a pdf viewer using this module. I am providing the link and have done it in both string format to test and as an object. I am not sure how to correct it and was hoping you could help.

Here is the error:
Uncaught Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. Check the render method of TestResultsDetail

I received this warning before the error too:
Warning: React.createElement: type is invalid -- expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in.

The module is installed and I imported just as described in the docs.

pdf.js requests for /[object%20Object] before loading proper URL

Hello, I am getting the following error when trying to load a pdf:

pdf.js:817 GET http://localhost:3000/[object%20Object] Util_loadScript @ pdf.js:817loader @ pdf.js:8081setupFakeWorkerGlobal @ pdf.js:8085PDFWorker_setupFakeWorker @ pdf.js:8267PDFWorker_initialize @ pdf.js:8260PDFWorker @ pdf.js:8166getDocument @ pdf.js:7646loadDocument @ react-pdf.js:195handleFileLoad @ react-pdf.js:138componentDidMount @ react-pdf.js:89(anonymous function) @ ReactCompositeComponent.js:264measureLifeCyclePerf @ ReactCompositeComponent.js:74(anonymous function) @ ReactCompositeComponent.js:263notifyAll @ CallbackQueue.js:67close @ ReactReconcileTransaction.js:81closeAll @ Transaction.js:204perform @ Transaction.js:151perform @ Transaction.js:138perform @ ReactUpdates.js:90flushBatchedUpdates @ ReactUpdates.js:173closeAll @ Transaction.js:204perform @ Transaction.js:151batchedUpdates @ ReactDefaultBatchingStrategy.js:63enqueueUpdate @ ReactUpdates.js:201enqueueUpdate @ ReactUpdateQueue.js:25enqueueSetState @ ReactUpdateQueue.js:210ReactComponent.setState @ ReactComponent.js:64_onChange @ Pages.jsx:17EventEmitter.emit @ events.js:74emitChange @ PageStore.js:58(anonymous function) @ PageStore.js:78_invokeCallback @ Dispatcher.js:198dispatch @ Dispatcher.js:174handleServerAction @ AppDispatcher.js:15loadedPages @ PageActionCreators.js:10(anonymous function) @ WebAPIUtils.js:66Request.callback @ client.js:721(anonymous function) @ client.js:536Emitter.emit @ index.js:133xhr.onreadystatechange @ client.js:825

Warning: setState(...): Can only update a mounted or mounting component.

Using versions 1.8.3 and 2.0.0beta I got this error. It happens every time, when I unmount my component before onDocumentLoad is called. I don't want to use this.isMounted() because it's considered anti-pattern. So is there any way to unsubscribe from async actions in componentWillUnmount? I think it should be somewhere inside Document component

warning.js:36 Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the PageTextContent component.

printWarning @ warning.js:36
warning @ warning.js:60
getInternalInstanceReadyForUpdate @ ReactUpdateQueue.js:48
enqueueSetState @ ReactUpdateQueue.js:200
ReactComponent.setState @ ReactBaseClasses.js:64
PageTextContent._this.onGetTextSuccess @ PageTextContent.js:64
Promise resolved (async)
getTextContent @ PageTextContent.js:135
componentDidMount @ PageTextContent.js:111
(anonymous) @ ReactCompositeComponent.js:265
measureLifeCyclePerf @ ReactCompositeComponent.js:75
(anonymous) @ ReactCompositeComponent.js:264
notifyAll @ CallbackQueue.js:76
close @ ReactReconcileTransaction.js:80
closeAll @ Transaction.js:206
perform @ Transaction.js:153
perform @ Transaction.js:140
perform @ ReactUpdates.js:89
flushBatchedUpdates @ ReactUpdates.js:172
closeAll @ Transaction.js:206
perform @ Transaction.js:153
batchedUpdates @ ReactDefaultBatchingStrategy.js:62
enqueueUpdate @ ReactUpdates.js:200
enqueueUpdate @ ReactUpdateQueue.js:24
enqueueSetState @ ReactUpdateQueue.js:209
ReactComponent.setState @ ReactBaseClasses.js:64
Page._this.onLoadSuccess @ Page.js:54
Promise resolved (async)
loadPage @ Page.js:151
componentDidMount @ Page.js:86
(anonymous) @ ReactCompositeComponent.js:265
measureLifeCyclePerf @ ReactCompositeComponent.js:75
(anonymous) @ ReactCompositeComponent.js:264
notifyAll @ CallbackQueue.js:76
close @ ReactReconcileTransaction.js:80
closeAll @ Transaction.js:206
perform @ Transaction.js:153
perform @ Transaction.js:140
perform @ ReactUpdates.js:89
flushBatchedUpdates @ ReactUpdates.js:172
closeAll @ Transaction.js:206
perform @ Transaction.js:153
batchedUpdates @ ReactDefaultBatchingStrategy.js:62
enqueueUpdate @ ReactUpdates.js:200
enqueueUpdate @ ReactUpdateQueue.js:24
enqueueSetState @ ReactUpdateQueue.js:209
ReactComponent.setState @ ReactBaseClasses.js:64
Document._this.onLoadSuccess @ Document.js:69
Promise resolved (async)
PDFDocumentLoadingTask_then @ pdf.js:2007
Document._this.onSourceSuccess @ Document.js:61
Promise resolved (async)
loadDocument @ Document.js:206
componentDidMount @ Document.js:149
(anonymous) @ ReactCompositeComponent.js:265
measureLifeCyclePerf @ ReactCompositeComponent.js:75
(anonymous) @ ReactCompositeComponent.js:264
notifyAll @ CallbackQueue.js:76
close @ ReactReconcileTransaction.js:80
closeAll @ Transaction.js:206
perform @ Transaction.js:153
perform @ Transaction.js:140
perform @ ReactUpdates.js:89
flushBatchedUpdates @ ReactUpdates.js:172
close @ ReactUpdates.js:47
closeAll @ Transaction.js:206
perform @ Transaction.js:153
perform @ ReactUpdates.js:89
flushBatchedUpdates @ ReactUpdates.js:172
closeAll @ Transaction.js:206
perform @ Transaction.js:153
batchedUpdates @ ReactDefaultBatchingStrategy.js:62
batchedUpdates @ ReactUpdates.js:97
dispatchEvent @ ReactEventListener.js:147

Incompatible with react v16

The current react-pdf version is incompatible with the newest react v16. In the newest version React.PropTypes were deleted.

But because in package.json we have "react": ">=15.5" we load this library with the incompatible version of react.

React v16 changes:

https://facebook.github.io/react/blog/2017/09/26/react-v16.0.html

"The deprecations introduced in 15.x have been removed from the core package. React.createClass is now available as create-react-class, React.PropTypes as prop-types, React.DOM as react-dom-factories, react-addons-test-utils as react-dom/test-utils, and shallow renderer as react-test-renderer/shallow. See 15.5.0 and 15.6.0 blog posts for instructions on migrating code and automated codemods."

Access to Worker using webpack

Using react-pdf 1.8.3 with webpack in hot reload mode. When I do import ReactPDF from 'react-pdf/build/entry.webpack' I get this error in Chrome:

Uncaught DOMException: Failed to construct 'Worker': Script at 'http://xxx:1235/assets/bundles/2c5a72550051ee999dc4.worker.js' cannot be accessed from origin 'http://yyy:8886'.

In Safari:

[Error] SecurityError (DOM Exception 18): The operation is insecure.

I found possible solution https://stackoverflow.com/questions/37718656/why-does-not-chrome-allow-web-workers-to-be-run-in-javascript but didn't check if it works

Ability to place custom HTML elements on a rendered page

This might be a bit of a niche use case, but it would be really nice if you could place custom HTML elements on a rendered page (i.e. relative to the element with class ReactPDF__Page). Something like:

...
render() {
    return (
        <Document
            file={getPDFURL()}
            loading={<LineLoader />}
            error={this.renderError()}
            onLoadSuccess={this.onLoadSuccess.bind(this)}
        >
            [...Array(this.state.numPages)].map((item, i) => (
                <Page key={`page-{i + 1}`} pageNumber={i + 1}>
                    <input type="text" name="text-field"  style={{position: 'absolute', left: 10, top: 10 width: '100px', height: '30px'}}  />
                </Page>
            )
        </Document>
    );
}
...

Wouldn't be too hard to implement I think?

loading object%20object instead of specified file

Hello,

i tried loading a pdf-file from url. All possibilities to include it failed with same error (file="http://localhost:3000/some/path/some.pdf", file={{ url: "http://localhost:3000/some/path/some.pdf"}}).

I tried using [email protected] after [email protected] failed. But the same error.

Here is what I get in chromium console:

Warning: Setting up fake worker. @ pdf.js: 273
GET http://localhost:3000/[object%20Object] @ pdf.js:893
Util_loadScript @ pdf.js:893
loader @ pdf.js:9418
setupFakeWorkerGlobal @ pdf.js:9422
PDFWorker_setupFakeWorker @ pdf.js:9641
(anonymous function) @ pdf.js:9554
(anonymous function) @ pdf.js:9561

My app is running on localhost:3000, but the path is different, as you might imagine.
Any help appreciated!

"Failed to load PDF" on the iPad

Hello,
Thank you for this very awesome package :)

I'm using it in my React app but I'm getting some error. It's working for every browser but not working only in Ipad (both chrome and safari browser)
Failed to load PDF

I am using your sample.jsx file. No modification in that file from your its an exact copy.
Loading base64 PDF string in {file} props.

react-pdf version : 2.1.1
react version : 15.6.1

Any idea about this issue? Am I doing something wrong?

Cannot find module 'worker-loader!./build/pdf.worker.js'

hello,

is there anything i have to do besides import { Document, Page } from 'react-pdf/build/entry.webpack' to use service workers? i'm running react-pdf 2.1.1 and nextjs (in case that's of any relevance).

thank you!
nicolai

index.js?d08fcf9:101 Cannot find module 'worker-loader!./build/pdf.worker.js'
Error: Cannot find module 'worker-loader!./build/pdf.worker.js'
    at Function.Module._resolveFilename (module.js:485:15)
    at Function.Module._load (module.js:437:25)
    at Module.require (module.js:513:17)
    at require (internal/module.js:11:18)
    at Object.<anonymous> ([...]/node_modules/pdfjs-dist/webpack.js:18:19)
    at Module._compile (module.js:569:30)
    at Module._compile ([...]/node_modules/source-map-support/source-map-support.js:483:25)
    at Object.Module._extensions..js (module.js:580:10)
    at Module.load (module.js:503:32)
    at tryModuleLoad (module.js:466:12)

Implement SVG rendering

SVG rendering is starting to be supported by PDF.js, so we should push forward as well. This technique gives us several advantages.

  • Improved rendering performance
  • Improved accessibility
  • TextLayers are gone; we're rendering text once and for good

To-dos

PoC stage

  • Investigate possibility of SVG rendering
  • Implement proof of concept

Alpha stage (separate branch)

  • Introduce renderMode flag to opt-in for SVG rendering
  • Resolve React-PDF SVG rendering issues
  • Report and monitor PDF.js SVG rendering issues
    • core-js placed in devDependencies mozilla/pdf.js#8890
    • SVG is ignoring viewport rotation
    • <svg:rect> attribute height: A negative value is not valid. ("-94.04")

Beta stage

  • Wait for Mozilla to announce SVG rendering production-ready
  • Switch default renderMode to SVG

Release statge

  • Resolve React-PDF reported SVG rendering issues

Future

  • Get rid of Canvas rendering altogether

TypeScript and definitions.

Im wondering if typings could be added/maintained for this project? Iv got a patch almost ready to go in my own repo i could add it?
Would it be too bold of me to even propose a conversion to TS?
bitmoji

ReferenceError: regeneratorRuntime is not defined with Create React App

I tried to use [email protected] with Create React App and I got this error.

Steps to reproduce:

npm install -g create-react-app
create-react-app test-pdf
cd test-pdf
npm install react-pdf@next --save
import React, { Component } from 'react';
import { Document, Page } from 'react-pdf'
import logo from './logo.svg';
import './App.css';

class App extends Component {
  render() {
    return (
      <div className="App">
        <Document>
          <Page />
        </Document>
      </div>
    );
  }
}

export default App;

I tried to install babel-polyfill and requires it before react-pdf but it didn't solve the issue.
It's mentionned in the README that babel-polyfill is required by the library if we don't use it but I didn't find where in the code?

react-pdf v2 and react-virtualized

I am trying to use the new version of this lib together with react-virtualized. As far as I can test so far I have managed to get this working with a fully responsive pdf viewer. The only problem is that I receive multiple (depending on the number of pages of the pdf) React warnings of the form

warning.js:36 Warning: setState(...): Can only update a mounted or mounting component. This usually means you called setState() on an unmounted component. This is a no-op. Please check the code for the Page component.

I have tried to track this down myself and although I am not sure about this at all, it seems it might be related to the fact that I use the CellMeasurer component from react-virtualized. From the react-virtualized documentation:

High-order component that automatically measures a cell's contents by temporarily rendering it in a way that is not visible to the user.

Not very clear how this is done, but I suspect that maybe this rendering is happening very fast and perhaps

componentWillUnmount() {
    if (this.runningTask && this.runningTask.cancel) {
      this.runningTask.cancel();
    }
  }

is not cancelling "quick" enough (i.e. setState({}) in onLoadSuccess()/onLoadError() is called even though Page has unmounted already). But at this point this is more speculation than something that I have been able to accurately verify. I also understand that this is not really a react-pdf issue per se, but nonetheless I was wondering if there perhaps is anyone who could shed some light on this matter.

'PDFJS' is not defined

I updated webpack of my project from 1.xx to 2.xx, But I could not make a build. I got this error. I could not find any solution. Do you have any idea?

Versions:

"webpack": "2.6.1",
"react": "15.4.*",
"react-pdf": "^1.8.3",

And errors:

./src/components/~/react-pdf/es5/react-pdf.js
(Emitted value instead of an instance of Error)
  Line 25:   'PDFJS' is not defined  no-undef
  Line 27:   'PDFJS' is not defined  no-undef
  Line 207:  'PDFJS' is not defined  no-undef

Thanks

Add support for custom PDF.js config

Adding a method of setting custom config that gets passed to it upon initiation would help resolve several issues the users are facing.

Examples:

  • In #84 setting workerSrc manually would help with side-loading worker.
  • In #62 setting cMapUrl would be the only way to get around CMaps not being bundled by default, while giving the users in need some way of resolving the issue.

Different directory for worker and bundle?

I am trying to use this library but unfortunately it is looking for the bundle and worker file at the root of the site instead of my custom directory /js/dist/ is there any way of set the path for worker and bundle js files?

Showing all pages at once

Hi @wojtekmaj, community,

Thanks for building and maintaining this lib !

While using the module, I have come across a UI where I need to show all pages of the pdf in a scrollable fashion. Currently what I do is along the lines of :

  1. Create a hidden div, load first page, save total number of pages to state.
  2. Map from [1...this.state.totalPages] and render <ReactPDF ... /> with relevant page number.

Here's what the map code looks like :

{(Array.from({length: this.state.totalPages}, (v, k) => k+1)).map((i) => {
              console.log(i)
              return (
                <div className='w-100 center tc mt3' key={i}>
                  <ReactPDF
                    width={screen.width*0.6}
                    file={'http://localhost:5000/assets/dance.pdf'}
                    pageIndex={i}
                    loading={this.renderLoader()}
                  />
                </div>
              );
            })}

This works, but sends out multiple requests (number of pages + 1) to the resource file. This leads to poor experience as the load time is too much.

Is there a cleaner solution for this ?

Thanks.

page-scrolling-spy

Help wanted.

Hi there, I want to build a feature that shows page number when user scrolling the pdf document. I tried insert from react-scroll into Page child but the Link component is parsed into text.... I wonder if there is a suggested way to implement it. Thank you!

<Document
	file={this.props.document.url}
	onLoadSuccess={pdf => this.initPDF(pdf)}
>
	{
		pages.map((page) => {
			return (
				<Page
					key={page + 1}
					pageNumber={page + 1}
					scale={scale}
				/>
			);
		})
	}
</Document>

SSR error

Hello, it seems I need your help

I have two projects: isomorphic React SPA and stateless UI components library. When I use react-pdf in the library, it's ok, but when I try to use my wrapper component which depends on react-pdf in the SPA, it fails.

This is the full trace:

.../tb-react-front/node_modules/teachbase-ui/lib/index.js:1
(function (exports, require, module, __filename, __dirname) { module.exports=function(modules){function __webpack_require__(moduleId){if(installedModules[moduleId])return installedModules[moduleId].exports;var module=installedModules[moduleId]={i:moduleId,l:!1,exports:{}};return modules[moduleId].call(module.exports,module,module.exports,__webpack_require__),module.l=!0,module.exports}var parentJsonpFunction=window.webpackJsonpteachbase_ui;window.webpackJsonpteachbase_ui=function(chunkIds,moreModules,executeModules){for(var moduleId,chunkId,i=0,resolves=[];i<chunkIds.length;i++)chunkId=chunkIds[i],installedChunks[chunkId]&&resolves.push(installedChunks[chunkId][0]),installedChunks[chunkId]=0;for(moduleId in moreModules)Object.prototype.hasOwnProperty.call(moreModules,moduleId)&&(modules[moduleId]=moreModules[moduleId]);for(parentJsonpFunction&&parentJsonpFunction(chunkIds,moreModules,executeModules);resolves.len

ReferenceError: window is not defined
    at /Users/labriko/Work/Teachbase/Teachbase3/tb-react-front/node_modules/teachbase-ui/lib/index.js:1:357
    at Object.<anonymous> (/Users/labriko/Work/Teachbase/Teachbase3/tb-react-front/node_modules/teachbase-ui/lib/index.js:1:2648)
    at Module._compile (module.js:624:30)
    at Module._extensions..js (module.js:635:10)
    at Object.require.extensions.(anonymous function) [as .js] (/Users/labriko/Work/Teachbase/Teachbase3/tb-react-front/node_modules/babel-register/lib/node.js:152:7)
    at Module.load (module.js:545:32)
    at tryModuleLoad (module.js:508:12)
    at Module._load (module.js:500:3)
    at Function.module._load (/Users/labriko/Work/Teachbase/Teachbase3/tb-react-front/node_modules/piping/lib/piping.js:218:16)
    at Module.require (module.js:568:17)

The problem is here (window is undefined in Node):

var parentJsonpFunction=window.webpackJsonpteachbase_ui;

Does react-pdf cause this error? When I remove react-pdf everything gets well
Thank you

Hi-DPI support

On devices with higher-than-standard resolution like Surface Pro 4 or an iPad, pdf.js renders blurry image, as it doesn't take into account that 'px' value is not equal to 1 physical pixel on the screen at all times.

We should detect the pixel density and render canvas in higher resolution on Hi-DPI devices.

Setting dynamic scale based on page width

Description

I want to scale PDF pages dynamically, based on page width and parent container <div/> width.

Question

Is this possible?

What I've tried

  • I've added scale variable to a state.
  • Then I recalculate scale in onPageLoad()
  • scale is calculated correctly but page is not rerendered correctly. Page component render is invoked but canvas is not being repaint.
  • When I change page, second page is being rendered correctly if scale was not changed.
    Code for my component below:
export default class PdfDocument extends React.PureComponent {
  constructor(props) {
    super(props);

    this.state = {
      numPages: null,
      pageNumber: 1,
      scale: 1.0
    };
  }

  // Custom pagination component
  onPageChange(pageNumber) {
    this.setState({ pageNumber: pageNumber + 1 });
  }

  onDocumentLoad({ numPages }) {
    this.setState({ numPages });
  }

  onPageLoad(page) {
    const parentDiv = document.querySelector('#pdfDocument')
    let pageScale = parentDiv.clientWidth / page.originalWidth
    if (this.state.scale !== pageScale) {
      this.setState({ scale: pageScale });
    }
  }

  render() {
    return (
      <div>
        <div id="pdfDocument">
          <Document
            file={url}
            onLoadSuccess={this.onDocumentLoad}
          >
            <Page
              pageNumber={this.state.pageNumber}
              onLoadSuccess={this.onPageLoad}
              scale={this.state.scale}
            />
          </Document>
        </div>
      </div>
    );
  }
}

uncaught TypeError: Cannot read property 'pageNumber' of null

uncaught TypeError: Cannot read property 'pageNumber' of null...

my code :
import React from 'react';
import ReactPDF from 'react-pdf';

class Example_pdf extends React.Component {
onDocumentLoad({ total }) {
this.setState({ total });
}

onPageLoad({ pageIndex, pageNumber }) {
    this.setState({ pageIndex, pageNumber });
}

render() {
    return (
        <div>
            <ReactPDF
                file='http://kostat.go.kr/file_total/kor3/korIp1_14.pdf'
                pageIndex={2}
                onDocumentLoad={this.onDocumentLoad}
                onPageLoad={this.onPageLoad}
            />
            <p>Page {this.state.pageNumber} of {this.state.total}</p>
        </div>
    );
}

}

export default Example_pdf;

i think the pdf file is not connected ...
how should i do???

Not working using browserify, but I don't know if it's still the cause

I tried 1.8.3 with Browserify, and I still have problems in running my app. Instead of trying to build the provided sample as I did discussing nnarhinen/react-pdf#39, this time I tried writing a minimal app from scratch. The issue looks different from before.

git clone https://bitbucket.org/lorenzostanco/reactpdf-browserify-test
cd reactpdf-browserify-test/
npm install
npm run build
npm run serve

PDF loading fails, and in the console I see:

GET http://127.0.0.1:8080/build.worker.js 404 (Not Found)
Warning: Setting up fake worker.
GET http://127.0.0.1:8080/build.worker.js 404 (Not Found)

Outline is always null

Using:

  • Version "react-pdf": "^2.1.1",
  • Browsers: All latest version of major browsers

When any PDF is loaded, including the example PDF that is on Mozilla's example page which clearly has a parsable outline, I'm seeing null.

the code below produces the following output:

Console Output

onLoadSuccess undefined
onParseSuccess {outline: null}

Code

import React, { Component, PropTypes as pt } from 'react';
import { Document, Outline, Page } from 'react-pdf/build/entry.webpack';

class Documents extends Component {
    constructor(props) {
        super(props);
        this.state = {
            pdf: false
        };

        this.onDocumentLoadSuccess = this.onDocumentLoadSuccess.bind(this);
    }

    onDocumentLoadSuccess (pdf) {
        this.setState({
            pdf: pdf
        });
    }

    render () {
        const { pdf } = this.state;

        return (<Document
            onLoadSuccess={this.onDocumentLoadSuccess}
            file={'./Sample.pdf'}>
                {pdf !== false ? <Outline
                    onLoadSuccess={(ol) => { console.log('onLoadSuccess', ol); }}
                    onLoadError={(ol) => { console.log('onLoadError', ol); }}
                    onParseError={(ol) => { console.log('onParseError', ol); }}
                    onParseSuccess={(ol) => { console.log('onParseSuccess', ol); }}
                    pdf={pdf}
                /> : null}
                {pdf !== false ? Array.from(
                    // Show the pages
                ) : null}
        </Document>);
    }
}

Update 1: not sure if these are pertinent to the issue:

  • pdf.getPageMode() yields a PromiseValue of UseNone
  • pdf.getPageLabels() yields a PromiseValue of null

Unexpected token <

Hi,

Thank you for maintaining this awesome package :)

I'm trying to use it in my React app but I get the following error in the console and the component is stuck on loading:

Uncaught SyntaxError: Unexpected token < http://project_server.dev/app_folder/d58d9dd3a5c5f2a8eafb.worker.js

I'm loading a base64 PDF served by my Laravel backend. I'm using webpack and everything seem properly set up. The base64 PDF seems file too.

Any idea what I'm doing wrong?

Many thanks

JavaScript heap out of memory

I'm experiencing memory errors on node build.
This is only the case when react-pdf is included and used in the project.

The command:

node react-scripts build

The error:

FATAL ERROR: CALL_AND_RETRY_LAST Allocation failed - JavaScript heap out of memory

I even added the memory argument

node --max-old-space-size=8192 react-scripts build

In the package.json

"react-pdf": "^2.1.1",

Please advice

pdf is rotated by default

when a pdf page's width is larger than height the page is rotated.
here is the render result:
qq20170904-164443 2x
and here is the file opened in Chrome:
qq20170904-164648 2x
here is the config:
<ReactPDF file={fileHeaders} pageIndex={pageIndex} onDocumentLoad={this.onDocumentLoad.bind(this)} onPageLoad={this.onPageLoad} loading={<div><Spin/></div>} width={width} style={{width:width, height:single?(height-40):'100%',overflowY:'auto', overflowX:'hidden',margin:'0 auto'}} />

display PDF in full screen

hello,

is there a more convenient way to display a PDF in full screen than to calculate the width based on the file's aspect ratio and the window size?

thank you!
nicolai

NPM pointing to the alpha version

I don't know if you are planning to release 2.0 soon, but I noticed NPM downloads the 2.0.0-alpha.7 listed here as "Pre-release", while this repo's master branch point to 1.8.3 which is marked as "Latest release".

$ npm install react-pdf
$ cat node_modules/react-pdf/package.json | grep version
  "version": "2.0.0-alpha.7"

onLoadSuccess called infinitely when file={someBlob}

I'm trying to use a Blob for the pdf value, but instead of calling onLoadSuccess once it calls it over and over ad nauseum.

import React, { Component, PropTypes } from 'react';
import { Page } from 'react-pdf';
import { Document } from 'react-pdf/build/entry.webpack';	// use entry.webpack to enable PDF.js worker
import b64toBlob from 'b64-to-blob';

export class PdfThumbnails extends Component {
	static propTypes = {
		b64data: PropTypes.string.isRequired,
	}

	constructor(props) {
		super(props);
		this.state = {
			numPages: 0,
		}
	}

	onDocumentLoad(x) {
		console.log(x);
                this.setState({ ...this.state, numPages:x.numPages });
    	}

	render() {
		const { b64data } = this.props;
		let fileBlob = b64toBlob(b64data);

		return (
			<div>
				<Document
					// file="/img/Catalist_identity.pdf"
					file={ fileBlob }
					onLoadSuccess={ this.onDocumentLoad.bind(this) }
				>
					<Page
						pageNumber={ 1 }
						scale={ 0.2 }
					/>
				</Document>
			</div>
		);
	}
}
export default PdfThumbnails;

Using a static file resource and the same onLoadSuccess method the component works great.

What I'm really doing here is using a base64 string as source data for , so an example of that would be very welcome. The one in #42 doesn't work for my flavor of ES..

Thanks!

Loading data URIs fails on Microsoft Edge

Likely due to pdf.js error in handling data URIs loading PDFs by passing data URIs fails with the following error:

Unexpected server response (0) while retrieving PDF (...)

  • Provide hotfix on our side
  • Report the error to Mozilla

Add support for rendering annotations

A work started by @flacerdk in #77.

  • Create annotations component, rendering annotation elements, add necessary flags - done by @flacerdk
  • Add necessary fields to test suite to enable testing
  • Fix annotations positioning
  • Ensure annotations are updated on changing scale, rotate and page
  • Ensure Mozilla's license allow us to copy annotations CSS
  • Update documentation
  • Test manually
  • Release beta & wait for feedback

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.