Git Product home page Git Product logo

react-pdf-js's Introduction

react-pdf-js

react-pdf-js provides a component for rendering PDF documents using PDF.js.


NPM Version NPM Downloads codecov

Demo

https://react-pdf.cousins.ai

Usage

Install with yarn add @mikecousins/react-pdf pdfjs-dist or npm install @mikecousins/react-pdf pdfjs-dist

usePdf hook

Use the hook in your app (showing some basic pagination as well):

import React, { useState, useRef } from 'react';
import { usePdf } from '@mikecousins/react-pdf';

const MyPdfViewer = () => {
  const [page, setPage] = useState(1);
  const canvasRef = useRef(null);

  const { pdfDocument, pdfPage } = usePdf({
    file: 'test.pdf',
    page,
    canvasRef,
  });

  return (
    <div>
      {!pdfDocument && <span>Loading...</span>}
      <canvas ref={canvasRef} />
      {Boolean(pdfDocument && pdfDocument.numPages) && (
        <nav>
          <ul className="pager">
            <li className="previous">
              <button disabled={page === 1} onClick={() => setPage(page - 1)}>
                Previous
              </button>
            </li>
            <li className="next">
              <button
                disabled={page === pdfDocument.numPages}
                onClick={() => setPage(page + 1)}
              >
                Next
              </button>
            </li>
          </ul>
        </nav>
      )}
    </div>
  );
};

Props

When you call usePdf you'll want to pass in a subset of these props, like this:

const { pdfDocument, pdfPage } = usePdf({ canvasRef, file: 'https://example.com/test.pdf', page });

canvasRef

A reference to the canvas element. Create with:

const canvasRef = useRef(null);

and then render it like:

<canvas ref={canvasRef} />

and then pass it into usePdf.

file

URL of the PDF file.

onDocumentLoadSuccess

Allows you to specify a callback that is called when the PDF document data will be fully loaded. Callback is called with PDFDocumentProxy as an only argument.

onDocumentLoadFail

Allows you to specify a callback that is called after an error occurred during PDF document data loading.

onPageLoadSuccess

Allows you to specify a callback that is called when the PDF page data will be fully loaded. Callback is called with PDFPageProxy as an only argument.

onPageLoadFail

Allows you to specify a callback that is called after an error occurred during PDF page data loading.

onPageRenderSuccess

Allows you to specify a callback that is called when the PDF page will be fully rendered into the DOM. Callback is called with PDFPageProxy as an only argument.

onPageRenderFail

Allows you to specify a callback that is called after an error occurred during PDF page rendering.

page

Specify the page that you want to display. Default = 1,

scale

Allows you to scale the PDF. Default = 1.

rotate

Allows you to rotate the PDF. Number is in degrees. Default = 0.

cMapUrl

Allows you to specify a cmap url. Default = '../node_modules/pdfjs-dist/cmaps/'.

cMapPacked

Allows you to specify whether the cmaps are packed or not. Default = false.

workerSrc

Allows you to specify a custom pdf worker url. Default = '//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjs.version}/pdf.worker.js'.

withCredentials

Allows you to add the withCredentials flag. Default = false.

Returned values

pdfDocument

pdfjs's PDFDocumentProxy object. This can be undefined if document has not been loaded yet.

pdfPage

pdfjs's PDFPageProxy object This can be undefined if page has not been loaded yet.

License

MIT © mikecousins

react-pdf-js's People

Contributors

andaleebroomy avatar boristian avatar danielrmay avatar dependabot-preview[bot] avatar dependabot[bot] avatar djsamseng avatar erikras avatar euglena1215 avatar freeslugs avatar gkedge avatar him0 avatar icyjoseph avatar joepio avatar johnogram avatar ksocha avatar maurish avatar michaeldeboey avatar mikecousins avatar newsiberian avatar nikoladev avatar nlepage avatar pitakill avatar prasannabrabourame avatar renatho avatar shinriyo avatar sugarshin avatar thenewlad avatar thomasvuillaume avatar viz avatar ziziana0507 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

react-pdf-js's Issues

local file not loading in windows

Local file not loading in in windows.
Error ::
UnknownErrorException {name: "UnknownErrorException", message: "ENOENT: no such file or directory, lstat 'C:\C:\Users\desktopappuser..\Crawling.pdf'",
details:"UnknownErrorException: ENOENT: no such file or directory, lstat 'C:\C:\Users\desktopappuser..\Crawling.pdf'"
message:"ENOENT: no such file or directory, lstat 'C:\C:\Users\desktopappuser..\Crawling.pdf'"
name:"UnknownErrorException"

File location is correct but react-pdf is adding an extra c:\

Error in node_modules

`ERROR in ./node_modules/react-pdf-js/lib/Pdf.js
02/02/2018 15:00:49Module not found: Error: Can’t resolve ‘pdfjs-dist/build/pdf.combined’ in ‘/app/node_modules/react-pdf-js/lib’
02/02/2018 15:00:49 @ ./node_modules/react-pdf-js/lib/Pdf.js 49:0-40
02/02/2018 15:00:49 @ ./node_modules/react-pdf-js/lib/index.js
02/02/2018 15:00:49 @ ./src/components/serviceHistory/index.js
02/02/2018 15:00:49 @ ./src/containers/adverts/index.js
02/02/2018 15:00:49 @ ./src/containers/main/index.js
02/02/2018 15:00:49 @ ./src/index.js
02/02/2018 15:00:49 @ multi ./src/index.js

Package size

Hi,

I've been using this library for some time now and it's great. The only strange thing is the size of the bundle once I have included this library. It increases at least 1MB in the file.

I'm planning to add support to dynamic imports but is there a way to reduce this size?

Thanks

Add onDocumentError prop for error handling

There is onDocumentComplete, but no onDocumentError prop function, which limits ability to handle errors. Also it looks like the internal (in Pdf.jsx) onDocumentError function is not called on errors.
Maybe because onDocumentError is defined as static.

all pages?

I have look through the code but could not find a method that renders all pages. Also i have not found something that works like the demo version on PDF.js Demo. Have i overlooked something?

well my original question was: Is there a way to render all pages without having to give it a page?

Loading... div

I can see we're adding a "Loading...", which the text can be customized. Is it possible to have a class on that div? In other words when it is loading, I want padding, but when the file had loaded I want no padding.

I tried to solve this with nth-child but when the canvas loads it also has a div surrounding it. I am stuck at this point unless I add padding to the div and negative padding on the canvas or some similar hack.

Disappear non-ascii string on pdf

Currently, react-pdf-js not show non-ascii content.
because, pdf.js fail to load cmap file.

GET http://localhost:8082/nullAdobe-Korea1-UCS2 404 (Not Found)

pdf-js test 2017-05-08 16-22-23

Original pdf: https://github.com/azu/react-pdf-js-non-ascii/blob/master/public/resources/presentation.pdf (I have expected to show this)

I can shown non-ascii string by some hack.
(This hack come from https://github.com/azu/pdf.js-controller/blob/29c3312400de23c8cfa5bb185700baddb0261a75/src/PDFJSController.js#L25-L26 )

// hack for non-ascii pdf content
// dynamic loading cMap files
window.PDFJS.cMapUrl = `/pdfjs-dist/cmaps/`;
window.PDFJS.cMapPacked = true;

pdf-js test 2017-05-08 16-24-31

Reproduce repository: https://github.com/azu/react-pdf-js-non-ascii

Is there any chance react-pdf-js support non-ascii content?

Does not support authorization headers.

This is supported in pdf.js using

docInitParams.httpHeaders

Seems we can fix this by updating this and passing to pdf.js.

    documentInitParameters: PropTypes.shape({
      url: PropTypes.string,
    }),

Someone from my team will submit a pr.

PDF's original rotate does not work properly when rotate props is used

Hi.

Given the PDF with metadata like below.

CropBox[0.0 0.0 842.4 595.44]
MediaBox[0.0 0.0 842.4 595.44]
Rotate 270

When pdf-react-js displays PDF file above without rotate props, PDF is displayed with the rotation angle of 270.

But when rotate props is set, e.g. 0, PDF's rotation angle will be 0, though expected rotation angle is 270.

It seems is caused by https://github.com/mikecousins/react-pdf-js/blob/master/src/Pdf.jsx#L310 step.

It seems that PDFPageProxy's rotate props is fetched and add to rotate props before pdf-react-js pass the rotate props to PDFPageProxy.getViewport.

Best regard

PDF not loading in microsoft Edge

The PDF is not getting opened in Edge 16. It gets stuck with preview screen saying "LOADING PDF". Do anyone have experienced the same issue?

Custom HTTP headers

Currently, only the document URL can be provided. For some URLs, one may need to pass additional information in HTTP headers (e.g. authentication tokens) of GET requests. PDF preview would currently fail to retrieve documents in these cases.

Changing file in the pdf component.

This part in componentWillReceiveProps makes it so that that i can change the pdf if i change the file prop, the problem is that i have to use documentInitParameters because without that i cannot pass other parameters to getDocument. But if i change the url in documentInitParameters the component will not rerender because its allways asking it file,content or binaryContent have been changed and if not it will not trigger loadPDFDocument even with

(newDocInit && docInit && newDocInit.url !== docInit.url)))

because newSource and oldSource are the same.

const newDocInit = newProps.documentInitParameters;
const docInit = this.props.documentInitParameters;

// Only reload if the most significant source has changed!
let newSource = newProps.file;
let oldSource = newSource ? this.props.file : null;
newSource = newSource || newProps.binaryContent;
oldSource = newSource && !oldSource ? this.props.binaryContent : oldSource;
newSource = newSource || newProps.content;
oldSource = newSource && !oldSource ? this.props.content : oldSource;

if (newSource && newSource !== oldSource &&
  ((newProps.file && newProps.file !== this.props.file) ||
  (newProps.content && newProps.content !== this.props.content) ||
  (newDocInit && newDocInit !== docInit) ||
  (newDocInit && docInit && newDocInit.url !== docInit.url))) {
  this.loadPDFDocument(newProps);
}

PDF images no longer maintain aspect ratio when resized in latest version

When upgrading to the latest react-pdf-js, PDF images now appear distorted when scaling them to a specified width.

Expected:
screen shot 2017-08-18 at 10 35 49 am

Actual:
screen shot 2017-08-18 at 10 36 55 am

Reproducible 100% of the time with this snippet:

<PDF
    className="w-100"
    onDocumentComplete={this.onDocumentComplete}
    binaryContent={{ data: this.props.checkImage }}
    page={this.state.pageNumber}
    scale={4}
/>

It seems that setting width: 100% scales the width correctly, but no longer scales the height to maintain aspect ratio as it did in previous versions, so the image becomes distorted.

Text layer not appearing (just canvas)

Trying with this PDF.
Am I missing something obvious?

Chrome 62, Windows 10. react-pdf-js v3.0.0.

export default class ReactPDF extends React.Component<any, any> {
  constructor(props: any, state: any) {
    super(props);

    this.state = {
      page: 1,
      pages: [],
    };
  }

  onDocumentComplete = (pages: any) => {
    this.setState({ page: 1, pages });
  }

  onPageComplete = (page: number) => {
    this.setState({ page });
  }

  render() {
    return (
      <div>
        <PDF file="EchoNarcissus.pdf"
          onDocumentComplete={this.onDocumentComplete}
          onPageComplete={this.onPageComplete}
          page={this.state.page} />
      </div>
    );
  }
}

how to setting headers??

i want to setting headers.
but error occurs...

sample 1)
<PDFJS
file="https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf"
httpHeaders={{'Cache Control': 'max-age=0, no-cache, no-store, must-revalidate', 'Access-Control-Allow-Origin': '*'}}
/>

error:
image

sample 2)
<PDFJS
file="https://mozilla.github.io/pdf.js/web/compressed.tracemonkey-pldi-09.pdf"
httpHeaders={{'Cache Control': 'max-age=0, no-cache, no-store, must-revalidate', 'Access-Control-Allow-Origin': '*'}}
/>

error:
image

how to setting headers??? please help me...

pdfjs-dist not working on server side rendering

Hi!

Can you please update pdfjs-dist dependency to use version 1.7.365 as this one works with server side rendering? Current version of pdfjs-dist being imported from react-pdf-js is crashing when reading variables like navigator, window and XMLHttpRequest in server side rendering.

Thanks in advance!

Warning: Setting up fake worker.

I am getting an issue where the PDF doesn't render sometimes, but sometimes it does. It will always appear when I click one of the pagination buttons, going to the next page or previous page. However, if I try changing the state, essentially doing what the pagination button does, this does not cause the PDF to appear. I notice that I am getting the warning: setting up a fake worker, which causes it to not work.

IE 11 Compatability Issue

One issue I'm currently experiencing are a couple of rendering issues with IE 11. I've been using the package with the file prop, passing in a url.

react-pdf-js

I've been able to fix the series of SCRIPT5045 errors by changing the Pdf.jsx file, line 290 to read:

canvas.style.cssText = style;

As for the (incredibly unhelpful) error message for the promise rejection type error that IE gives me, I'm not sure where to look for that.

Apologies if this has been touched before, or is an issue outside of this library. I looked through the closed issues and saw a single closed ticket for IE11 issues that didn't provide enough info. Hopefully, I'm not missing anything.

Issue does not occur in Chrome, Firefox, or Edge.

Thanks for this library, it's been excellent so far!

Is there a way to load a PDF from base64 data?

Loading a PDF from react-pdf worked this way, could anyone help me out with this?

I'm getting a PDFDocument: stream must have data error whenever I try to load my PDF's

<PDF
          file={`data:application/pdf;base64,${this.state.base64}`}
          onDocumentComplete={this.onDocumentComplete}
          onPageComplete={this.onPageComplete}
          page={this.state.page}
/>

When minified with webpack I get lots of invalid XRef stream errors and no rendered PDF

I am using this in a ReactQL app which is working fine in the development build however when I build for production, using the same PDFs results in a tonne of errors and no rendered PDF - it does get the page count and loads the UI, I can navigate between pages as well which causes more error messages in the console on each page change.

Errors:

Warning: Ignoring invalid character "64" in hex string
    Error: Invalid XRef stream
vendor.dad8511….js:1     at l (http ://production.url/vendor.dad8511370caffccccd9.js:1:239375)
    at e.readXRef (http ://production.url/vendor.dad8511370caffccccd9.js:1:647134)
    at e.parse (http ://production.url/vendor.dad8511370caffccccd9.js:1:642733)
    at e.setup (http ://production.url/vendor.dad8511370caffccccd9.js:1:746429)
    at e.parse (http ://production.url/vendor.dad8511370caffccccd9.js:1:745072)
    at http ://production.url/vendor.dad8511370caffccccd9.js:1:885895
at Promise (<anonymous>)
    at ensure (http ://production.url/vendor.dad8511370caffccccd9.js:1:885827)
    at ensureDoc (http ://production.url/vendor.dad8511370caffccccd9.js:1:885002)
vendor.dad8511….js:1 Warning: Indexing all PDF objects
vendor.dad8511….js:1 Error: Bad FCHECK in flate stream: 72, 253
vendor.dad8511….js:1     at l (http ://production.url/vendor.dad8511370caffccccd9.js:1:239375)
    at e (http ://production.url/vendor.dad8511370caffccccd9.js:1:262579)
    at e.makeFilter (http ://production.url/vendor.dad8511370caffccccd9.js:1:333144)
    at e.filter (http ://production.url/vendor.dad8511370caffccccd9.js:1:332708)
    at e.makeStream (http ://production.url/vendor.dad8511370caffccccd9.js:1:332548)
    at e.getObj (http ://production.url/vendor.dad8511370caffccccd9.js:1:328798)
    at e.fetchUncompressed (http ://production.url/vendor.dad8511370caffccccd9.js:1:648485)
    at e.fetch (http ://production.url/vendor.dad8511370caffccccd9.js:1:647883)
    at e.fetchIfRef (http ://production.url/vendor.dad8511370caffccccd9.js:1:647626)
vendor.dad8511….js:1 Warning: Invalid stream: "Error: Bad FCHECK in flate stream: 72, 253"

@leebenson any ideas?

CORS ?

It leaves this on the screen:

Unhandled Rejection (UnexpectedResponseException): 
Unexpected server response (0) while retrieving PDF "http://www.neeq.com.cn/disclosure/2014/1231/64673196.pdf".

and this on the console:

Warning: Setting up fake worker.

XMLHttpRequest cannot load http://www.neeq.com.cn/disclosure/2014/1231/64673196.pdf. 
No 'Access-Control-Allow-Origin' header is present on the requested resource. 
Origin 'http://localhost:3000' is therefore not allowed access.


while network request of this PDF yields 206 Partial Content.

This PDF is not on my server, it's other people's server, I can't change CORS setting of it. How can I get this PDF file without CORS problem?

code:

            <PDF
              className="reportpdf"
              file={this.state.source.replace(/^http:/, "https:")}
              page={1}
            />

Password support?

It doesn't seem the password required callbacks are being passed to PDFJS.getDocument
Am I right? Or did I miss something? Could it be added? Should be something like:

var pw = "asd";
var passwordCB = function(passwordFunc, reason){
    debugger;
    if (reason === 1) { // need a password
        passwordFunc(pw);
    } 
    else { // Invalid password
        alert('Invalid!');
        return;
    }
      
}
PDFJS.getDocument(url, null, passwordCB, null)

And tie that somewhere with the react code.

How can we print.

Is possible add a function to print the pdf. or do you know how to do it.?
thanks

'worker-loader' requires 'webpack' as peerDependency

When I install react-pdf-js in a clean repo, I get the following warnings:

npm WARN [email protected] requires a peer of react@>=15 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of react-dom@>=15 but none is installed. You must install peer dependencies yourself.
npm WARN [email protected] requires a peer of webpack@^2.0.0 || ^3.0.0 but none is installed. You must install peer dependencies yourself.

react& react-dom are marked as peerDependencies, but webpack isn't.
Please add webpack to the peerDependencies, since this is a peerDependency of worker-loader, which is a dependency of pdfjs-dist.

I've added a similar issue upstream, so pdfjs-dist will list webpack as a peerDependency (mozilla/pdf.js#9248).

It doesn't rerender when binaryContent changes

When rendering a PDF by binaryContent, such as:

<PDF binaryContent={this.props.file} />

It doesn't rerender when binaryContent changes because componentWillReceiveProps doesn't check for changes in this prop to call this.loadPDFDocument(newProps):

if (newSource && newSource !== oldSource &&
    ((newProps.file && newProps.file !== this.props.file) ||
    (newProps.content && newProps.content !== this.props.content) ||
    (newDocInit && JSON.stringify(newDocInit) !== JSON.stringify(docInit)))) {
    this.loadPDFDocument(newProps);
}

When next release is planned?

We have a problem with IE11 with react-pdf-js(v.3.0.4).

34736760-023799a2-f542-11e7-87e4-e3ad73df20d7

But we know that this was fixed few days ago in issue (#57). When you planning next release? Thanks.

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.