0

As the titles suggests, I would like to extract the data itself (content) of the pdf page/s using the react-pdf library, and then parse the data by myself.
I wasn't able to find any source on that matter, so I very well may have led myself into confusion with how it works.

https://www.npmjs.com/package/react-pdf

I have no snippet to share, since this is a conceptual question.

korkotyan
  • 53
  • 9

1 Answers1

0

One way to do that is to render the text layer by setting the Page prop renderTextLayer to true:

renderTextLayer={true}

and getting the text with the props:

onGetTextSuccess={
                    (text) => console.log(text)
                }

Since I didn't want to display the text layer but wanted to get the text, I had to hide the layer with css.

An example Code:

    import React, {useState} from 'react';
    import { Document, Page, Outline } from 'react-pdf/dist/esm/entry.vite';
    import samplePFDF from '/../example.pdf';

    export default function PdfViewer() {
      const [numPages, setNumPages] = useState(null);
      const [pageNumber, setPageNumber] = useState(1);

      function onDocumentLoadSuccess({ numPages }) {
        setNumPages(numPages);
      }

      function formatText(texts) {
        let textFinal = ''
        for (let i = 0; i < texts.items.length; i++) {
            textFinal += texts.items[i].str
        }
        console.log(textFinal)
      }

      return (
        <div>
            <Document file={samplePFDF} onLoadSuccess={onDocumentLoadSuccess}>
                <Page pageNumber={pageNumber} renderAnnotationLayer={false} 
                   renderTextLayer={true} onGetTextSuccess={
                    (text) => formatText(text)
                } onGetTextError={(e)=> console.log(e)}/>
                <Outline/>
            </Document>
            <p>
                Page {pageNumber} of {numPages}
            </p>
        </div>
    );
  }