Giter Club home page Giter Club logo

react-pdf-highlighter's Introduction

โ˜•๏ธ Buy me a coffee

Node CI

react-pdf-highlighter

react-pdf-highlighter is a React library that provides annotation experience for PDF documents on web. It is built on top of PDF.js by Mozilla. Text and rectangular highlights are supported. Highlight data format is independent of the viewport, making it suitable for saving on the server.

Example

For online example check https://agentcooper.github.io/react-pdf-highlighter/.

To run the example app locally:

npm install
npm start

Create React App example is available in ./create-react-app-example. Make sure to run npm install there as well.

Installation

npm install react-pdf-highlighter

See ./example/src/App.tsx for React component API example.

Prior art

react-pdf and react-pdfjs only provide React wrappers for PDF.js and do not have built-in annotation functionality.

pdfjs-annotate does not provide text highlights out of the box.

PDF.js provides only viewer:

PDF.js is mainly written for reading PDF files, not editing them. Because of that we don't yet support adding any kind of annotations. We do however support rendering a number of annotation types for viewing.

See also:

FAQ

Can I get a new PDF with the highlights embedded into the document?

Take a look at https://pdf-lib.js.org.

Wasn't this named react-pdf-annotator at some point?

Yes, but people from https://www.pdfannotator.com/ asked me to rename, since they have a trademark for PDF Annotator.

I'm trying the demo with my PDF and it is not loading!

Please check the CORS headers on your url. It is required for the cross-domain request.

Compatibility

Works in Google Chrome, Safari 10+, Firefox 52+. Not tested in Internet Explorer.

react-pdf-highlighter's People

Contributors

acco avatar agentcooper avatar albcunha avatar amihay-hellofyllo avatar arpitbhalla avatar cbwchuck avatar dependabot[bot] avatar fensterbank avatar fpaupier avatar jeager avatar jinman avatar joebutler2 avatar jonasgruenwald avatar jonathanbyrne avatar jsg2021 avatar mapreal19 avatar marcelodlr avatar oscarbc avatar serizawa-jp avatar steevn avatar stephensamra avatar varung avatar yasuhara-shota avatar z4m0 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

react-pdf-highlighter's Issues

PdfLoader(...): Nothing was returned from render.

hi, I used react-pdf-highlighter as a npm package in my project, and I import PdfLoader in a tsx file, but I got some mistakes.

  • there is my code
// index.tsx
import {
  PdfLoader,
  PdfHighlighter,
  Tip,
  Highlight,
  Popup,
  AreaHighlight,
} from 'react-pdf-highlighter';
...
export default function PDFViewer(){
  ...
  return (
    <PdfLoader url={url}>
          {(pdfDocument: any) => (
            <PdfHighlighter
              ...
            />
          )}
    </PdfLoader>
  )
}
  • there is the mistake
Uncaught Error: PdfLoader(...): Nothing was returned from render. This usually means a return statement is missing. Or, to render nothing, return null.
    at reconcileChildFibers (react-dom.development.js:15622)
    at reconcileChildren (react-dom.development.js:18070)
    at finishClassComponent (react-dom.development.js:18471)
    at updateClassComponent (react-dom.development.js:18404)
    at beginWork$1 (react-dom.development.js:20161)
    at HTMLUnknownElement.callCallback (react-dom.development.js:336)
    at Object.invokeGuardedCallbackDev (react-dom.development.js:385)
    at invokeGuardedCallback (react-dom.development.js:440)
    at beginWork$$1 (react-dom.development.js:25738)
    at performUnitOfWork (react-dom.development.js:24662)
    at workLoopSync (react-dom.development.js:24638)
    at performSyncWorkOnRoot (react-dom.development.js:24237)
    at react-dom.development.js:12180
    at unstable_runWithPriority (scheduler.development.js:818)
    at runWithPriority$2 (react-dom.development.js:12130)
    at flushSyncCallbackQueueImpl (react-dom.development.js:12175)
    at flushSyncCallbackQueue (react-dom.development.js:12163)
    at scheduleUpdateOnFiber (react-dom.development.js:23676)
    at Object.enqueueSetState (react-dom.development.js:13975)
    at DynamicComponent../node_modules/react/cjs/react.development.js.Component.setState (react.development.js:325)

Right click is disabled

Thanks for the wonderful tool!

It appears this disables right-clicking anywhere on the page where a PDF is loaded (see demo). Is this intentional? Would be great to retain right-click support outside of the PDF document.

Best,
Anthony

Adding page borders /margins

Hey @agentcooper thanks for putting together this sample, it's been very helpful. I'm trying to add back page borders and other margin/padding, but having trouble adjusting the highlight layer to accomodate. How would someone compensate for these margins in the highlight layer?

Not working

Hello.
I installed it and i got a lot of problems with security packages and I ran "npm audit fix" but using url pdf or local pdf file not work.
Could you please debug it, and if is possible try it on windows plataform because i got architecture warns.

Accessing the PDF content

Is there a way to send the PSD (with highlights) as base64 to a server, for example after a highlight is added or.
I don't care if the highlights are merged and won't be able to alter them after save, but so far this is the tool that would help me in my project and seems to work perfectly. Saving is the only thing i couldn't spot in your docs/code (I might be blind though)

Determine row(line) number of highlighted text in a page

Hello,

I have a requirement to find a row(line) number and column number of highlighted text in a page. I have tried a method of considering the top and bottom of the selected text from the boundingRect and and calculate the row number. Since the boundingRect returns different values depending on the text, this method didn't show to be effective. I would appreciate and leads in computing row(line) number and column number. Thanks.

getting this error please solve

[email protected] start C:\Users\anoop\Downloads\react-pdf-highlighter-master

nwb serve-react-demo

'nwb' is not recognized as an internal or external command,
operable program or batch file.
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! [email protected] start: nwb serve-react-demo
npm ERR! Exit status 1
npm ERR!
npm ERR! Failed at the [email protected] start script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.
npm WARN Local package.json exists, but node_modules missing, did you mean to install?

npm ERR! A complete log of this run can be found in:
npm ERR! C:\Users\anoop\AppData\Roaming\npm-cache_logs\2019-05-27T04_46_16_241Z-debug.log

How to use this plugin in React project

Hi Team/@agentcooper

I want to highlight spot in PDF and also I need to find page number and coordinates of that PDF. Please anyone let me know the steps how can I use this plugin in my React project.

I don't find any steps how to use this plugin in React project.

Note: I'm able to download this code and able to run the code locally but I need to use this as a plugin in my project.

Thanks in Advance!

Cannon open others pdf files

Hello i can't use others pdf files, you can try changing

state = { highlights: testHighlights[url] ? [...testHighlights[url]] : [] };
with
state = { highlights: [] };

AND
const DEFAULT_URL = "https://arxiv.org/pdf/1708.08021.pdf";
with
const DEFAULT_URL = "https://www.antennahouse.com/XSLsample/pdf/sample-link_1.pdf"

Others url are not working these include mine, Could you help me?
https://depts.washington.edu/owrc/Handouts/Hacker-Sample%20MLA%20Formatted%20Paper.pdf
http://www.pdf995.com/samples/pdf.pdf

Convert screenshot when load

IIn Sidebar.js I have seen

<img src={highlight.content.image} alt={"Screenshot"} />

In my case I only have the coordinates of the boundingRect I want to display. What is the easiest way to create the image (content.image) from the HTMLCanvas when the page loads the first time?

In the demo/sr/App.js the image is first rendered when the boundingRect changes

                 <AreaHighlight
                      highlight={highlight}
                      onChange={boundingRect => {
                        this.updateHighlight(
                          highlight.id,
                          { boundingRect: viewportToScaled(boundingRect) },
                          { image: screenshot(boundingRect) }
                        );
                      }}
                    />

highlight co-ordinates are changing from screen to screen

Hi @agentcooper,

Highlight co-ordinates are changing from screen(15.6) to screen(17.3). But when I add highlight with 17.3 and try to navigate that highlight from 15.6. It is automatically highlighting the exact place.

How you are achieving this functionalities without maintaining metadata information of client screen.

I am trying to achieve pdf text extraction with bounding box and with that some important tet bounding box I am trying to navigate in reac-pdf-highlighter.

I want to match this two bounding box.

Please do help me in this ASAP.

errors related to 'react-rnd' package version

To help others:

At first, I was using the latest version of react-rnd, which was > 10.x.x, and got the following error

You likely forgot to export your component from the file it's defined in, or you might have mixed up default and named imports

After checking the source code, I installed the version ^7.1.5 and it works fine now.

Component PdfLoader does not refresh when pdfFileUrl changes

I managed to set up an application based on the example of this repo with electron.js, I added a button to load new pdf files. The highlight sidebar updates every time when I load a new pdf file and its associated annotations, but component does not refresh.

I tried to create a simple component such as

const DemoComp = (props) => (
        <h2>{props.pdfFileUrl}</h2>
);
...       
{pdfFileUrl ? (
          <DemoComp pdfFileUrl={pdfFileUrl} />
) : null

the DemoComp updated as expected so the React state and its refresh cycle are working properly.

@agentcooper May you please give me some hints to resolve the issue?

thanks

Word are merging without space.

Hi @agentcooper.

If you see the sample deployed in https://agentcooper.github.io/react-pdf-highlighter/.

You have some predefined highlighted text. In that, one line highlighted as Impressive and highlighted text on right side panel is millions of lines of code atFacebookevery day

But actual content on pdf looks with space like millions of lines of code at Facebook every day.

So the problem is there should be space between at Facebook every day

So please help me in solving this.

Selection Box (how do you create one?)

Hi,

In the demo, you have a resizable bounding box around some JS code snippet. How do you create that? I assume some keyboard shortcut? It's great for annotating image regions, charts, etc, but not sure how to create a selection box. Do you mind explaining?

Using custom path for worker.js

Hi,
Can you please tell how to provide a custom worker.js path to react-pdf-highlighter.
pdfjs gives it in their options
pdfjsLib.GlobalWorkerOptions.workerSrc = '<any relative or absolute path>';
So that we have workaround for issues like compatibility with webpack 4 and worker files not able to load on environments like nextjs.

Any way to disable emojis?

Hi,

First of all, thanks a lot for this library, it is pretty awesome. The only thing that I would like to tweak is to disable emojis on the comments. I have been checking around and I can hide the emojis that are being printed, but I cannot hide the input type emojis when adding the comment (there isn't any class or CSS selector that I can use as far as I know). Any way that we could disable them through a parameter in Tip or so? Thanks!

dynamic highlighting from passages

Hello there...

Is is possible to dynamically hightlight from text? I have an app that searches information on pdf's and present the users a list of results. Each results is a paragraph. I would like to present the option of opening the PDF and show the found passage highlighted. I've been looking at the code, but the coordinates from the examples is hardcoded. I see that you can manually highlight text, but i didn't find a way to programatically calculate the coordinates search by searching text.

Thanks! And kudos, great library!

adaptive problem

How to make the width of the pdf document zoom in with the size of the container

<div style={{width: flag ? winWidth * 0.88 : winWidth * 0.63, position: "relative"}}>
    <PdfLoader url={this.state.url}>
        {
            pdfDocument=> (<PdfAnnotator {...props}/>)
        }
    </PdfLoader>
</div>

Delete a highlight

Hello, I would like remove a highlight when I click on "X" letter, placed before highlight.comment.text. Do you have any solution?

Could you help me?.

Uncaught (in promise) TypeError: (rects || []).map is not a function

Hello i have an error,

Im working with web services to save annotations, when i retrive data (similar to test-highlights.js)
and i have this error.

Uncaught (in promise) TypeError: (rects || []).map is not a function at PdfAnnotator.scaledPositionToViewport (PdfAnnotator.js:232) at PdfAnnotator.proxiedMethod [as scaledPositionToViewport] (createPrototypeProxy.js:44) at PdfAnnotator.js:279 at Array.map (<anonymous>) at _loop (PdfAnnotator.js:274) at PdfAnnotator.renderHighlights (PdfAnnotator.js:268) at PdfAnnotator.proxiedMethod [as renderHighlights] (createPrototypeProxy.js:44) at PdfAnnotator.componentWillReceiveProps (PdfAnnotator.js:119) at PdfAnnotator.proxiedMethod [as componentWillReceiveProps] (createPrototypeProxy.js:44) at ReactCompositeComponent.js:610

"Error: You are using old position format, please update" when selecting across pages

Hi, thanks for your work on this great library!

I seem to have found a bug that will crash my react app when attempting to select and highlight text across pages.

It's possible to reproduce this in the demo app, it only throws an error in the console in that case though.
For some reason I can only reliably reproduce it in chromium, it does happen in Firefox, but not every time.

Steps to reproduce:

The chrome console shows this error:

Uncaught Error: You are using old position format, please update
    at i (coordinates.js:58)
    at t.scaledPositionToViewport (PdfHighlighter.js:225)
    at PdfHighlighter.js:273
    at Array.map (<anonymous>)
    at f (PdfHighlighter.js:268)
    at t.renderHighlights (PdfHighlighter.js:262)
    at t.<anonymous> (PdfHighlighter.js:501)
    at e.notifyAll (CallbackQueue.js:74)
    at i.close (ReactUpdates.js:57)
    at i.closeAll (Transaction.js:207)

When actually adding the highlight now, clicking on it in the sidebar will throw more errors with You are using old position format, please update and not scroll to any location. There is also no highlight added to the two pages.

If there is no way to fix this, would there be a way to catch this error somewhere when using the library so I can just output a message telling the user not to select across pages or something?
I don't find it really necessary to allow this anyway, but users might do it and crash the app.

Get PDF Coordinates from Selection

I'm looking for a way to get PDF coordinates/points from a highlighted rectangular selection. So far I've been able to understand that the PDFHighlighter component is using both scaled and viewport coordinates for my selections, however I'm not able to figure out where or if I can extract actual PDF coordinates from them. Can anyone point me in the right direction for this?

pdfjs.worker not found when using with webpack

Hi, I am trying to use your library with webpack, but unfortunately I am getting an error due to webpack not able to find a path to pdf.worker.

0.dll.js:1 Uncaught ReferenceError: webpackJsonp_name_ is not defined
    at 0.dll.js:1

The source.js looks like


/***/ "./node_modules/pdfjs-dist/build/pdf.worker.js":
/***/ (function(module, exports, __webpack_require__) {

eval("/* WEBPACK VAR INJECTION */ ...
/***/ })

})

I found this thread, but don't have enough experience to fix it myself.

Any idea how to make it work?

Collaboration with polar-bookshelf

Afternoon.

I'm the author of polar-bookshelf...

and I thought it might make sense to introduce myself and see if we can collaborate on PDF annotation:

https://github.com/burtonator/polar-bookshelf

The goals of Polar are pretty ambitious. It started out as a set of scripts for managing my growing pile of books and research papers that I was reading and is now more of a larger product around web annotation starting as an Electron app.

Right now we have a beta release and another bit beta due out early next week.

The big change is that we're adding support for HTML by capturing pages and rendering them locally.

I'm probably going to migrate everything to React + Redux. Internally this is sort of the model I wanted to go with but I didn't think this was going to be a large project at the time.

Right now one of the biggest challenges we have is with the annotation component. I'd like to support a rich annotation model including comments, pagemarks, bookmarks, notes, flashcards, icons, etc.

We're still refactoring the code and initially I didn't want to go with react-pdf-highlighter because it used react and I didn't want to swallow using a framework. But it might make sense to since we're going in that direction anyway.

Angular support?

Just a question, not an issue. Can this be leveraged inside an angular app or has anyone re-written it to work in Angular? Or have you heard of something similar that would work in Angular?

Thanks,
Donnie

how to use it?

Hi @agentcooper, I have a noob question.

Is it implemented in typescript language? I am a bit confused by strong typing in the code.
NB: I am a javascript beginner.

Load pdf after ComponentDidMount

Hi,

I am trying to load a pdf from an external source. The external source address comes from an external API. But it seems that I'm hitting a chicken and egg situation because I can't get PdfLoader to wait for the result to load the PDF

I tried calling the API to retrieve the URL from both ComponentDidMount and ComponentWillMount, but the page breaks with Unhandled Rejection (InvalidPDFException): Invalid PDF structure before the state is updated with URL.

Is there a way to tell PdfLoader to wait for all promises to be fulfilled before attempting to load the PDF?

Next.js error

I am getting this error while using it in next.js

image

Render PDF page by page

Is there a way to render the PDF document page by page instead of rendering the whole PDF file as a scroll-able vertical view?

Getting data from web service. not working

Hello, i have an error when i have to setState with data from webservice.

componentDidMount() {
window.addEventListener(
"hashchange",
this.scrollToHighlightFromHash,
false
);
request('GET', url_ws).done((res) => {
if(res.statusCode==200){
parseString(res.getBody(),{explicitArray:false}, function (err, result) {
console.log(result['root']['element']);//getting data from xml and parsing to json
this.setState({ highlights: testHighlights});//ERROR: Cannot read property 'setState'
});
}else{
console.log("asd")
}
});

Not being able to run the sample using yarn

Hi @agentcooper
I was trying to run the sample by doing the following commands, using yarn 1.3.2

yarn
yarn build
yarn start

There are no errors doing this process, but when I go to localhost:3000 nothing appears on the screen
The following errors appear on the console

Uncaught TypeError: Cannot read property 'TextLayerBuilder' of undefined
    at Object.<anonymous> (PdfAnnotator.js:44)
    at Object../src/components/PdfAnnotator.js (PdfAnnotator.js:604)
    at __webpack_require__ (bootstrap aed3d04f67b98f5b9c55:707)
    at fn (bootstrap aed3d04f67b98f5b9c55:112)
    at Object../src/index.js (index.js:3)
    at __webpack_require__ (bootstrap aed3d04f67b98f5b9c55:707)
    at fn (bootstrap aed3d04f67b98f5b9c55:112)
    at Object.<anonymous> (bootstrap aed3d04f67b98f5b9c55:805)
    at Object../demo/src/App.js (App.js:214)
    at __webpack_require__ (bootstrap aed3d04f67b98f5b9c55:707)

Nevertheless if I use npm 5.6.0
Everything goes well
Perhaps package.json.lock prevented this crash by locking the dependency

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.