Search code examples
javascriptasp.net-mvcpdfpdf.js

Unable to specify custom path for pdf.worker.js in PDFjs


I have implemented PDFjs in my ASP.NET MVC application. The steps which I have followed.

  • Created an action that works as Pdf Viewer by copying the code provided by PDFjs as WebViewer.html.
  • On this page, I properly provided paths to all the static resources that are required by this HTML page.

Now the only problem is the path of pdf.worker.js. When I run the application, I get an error that this file not found. Even after lots of efforts, I am not able to fix this issue. Can anybody tell me that where I need to make a change in the code so that I can specify a custom path to this file?

enter image description here

As per code, I can say that this js file is internally referenced by pdf.js. But pdf.js file seems to be generated by WebPack and updating pdf.worker.js path in this file not affecting anything.

This is how pdf.js code looks like:

enter image description here


Solution

  • Using the PDF.js default viewer, the application options are in the viewer.js file. While I don't have a complete understanding of exactly how it works, it seems the viewer layer passes configuration values to the pdf.js display layer as necessary.

    In version 2.0+, you can change the hard-coded value for workerSrc, which looks like this by default:

    workerSrc: {
      value: '../build/pdf.worker.js',
      kind: OptionKind.WORKER
    }
    

    I couldn't figure out a way to dynamically set this in 2.0.

    In the newly pre-released 2.1, thanks to this pull request, you can use the custom webviewerloaded event to more easily set viewer options. For example,

    document.addEventListener('webviewerloaded', function () {
        document.PDFViewerApplicationOptions.set('workerSrc', '/your/path/here/pdf.worker.js');
    });