Saturday, 23 January 2021

Mozilla PDF - how to view PDFs from url in react app?

I have followed a quick tutorial on how to implement Mozilla's PDF viewer with React. I have made a codesanbox here. I would like to know if this is possible to implement with importing node module of pdfjs. So, instead of downloading the package in to public folder to use it with import:

export default class PDFJs {
  init = (source, element) => {
    const iframe = document.createElement("iframe");

    iframe.src = `/pdfjs-2.5.207-dist/web/viewer.html?file=${source}`;
    iframe.width = "100%";
    iframe.height = "100%";

    element.appendChild(iframe);
  };
}

Also, this kind of setup doesn't work when PDF's source is an URL. If I do that I get an error:

PDF.js v2.5.207 (build: 0974d6052) Message: file origin does not match viewer's

I have commented out the part of the code where it checks the file's origin in pdfjs-2.5.207-dist/web/viewer.js:

  //if (origin !== viewerOrigin && protocol !== "blob:") {
  //  throw new Error("file origin does not match viewer's");
  //} 

But, then I got an error:

PDF.js v2.5.207 (build: 0974d6052) Message: Failed to fetch

How can I fix this? Is it possible to import this package like a module into react component and how can I use it for PDF's from external resources with URL?



from Mozilla PDF - how to view PDFs from url in react app?

No comments:

Post a Comment