Created
February 18, 2021 22:39
-
-
Save Genkilabs/a5285020ca548f589b9c46497afca941 to your computer and use it in GitHub Desktop.
Workaround for running pdf.js on Rails 6.1 Ruby 3.0 with webpacker
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//app/assets/js/any_es6_module.js | |
//Use globally in any es6 module you are requiring through application.js | |
var render_pdf_thumbnail = function(pdfData, $canvas) { | |
//This is the sauce. We instantiate a new Worker from our globally scoped worker-loader f() | |
pdfjsLib.GlobalWorkerOptions.workerPort = new pdfjsWorker(); | |
// In my case, using DocumentInitParameters object to load binary data. | |
var loadingTask = pdfjsLib.getDocument({data: pdfData}); | |
loadingTask.promise.then(function(doc) { | |
var pages = []; while (pages.length < doc.numPages) pages.push(pages.length + 1); | |
return Promise.all(pages.map(function (num) { | |
// create a div for each page and build a small canvas for it | |
return doc.getPage(num).then(makeThumb) | |
.then(function (pdfCanvas) { | |
Object.assign(pdfCanvas.dataset, $canvas[0].dataset); | |
$canvas.replaceWith(pdfCanvas); | |
}); | |
})); | |
}).catch(console.error); | |
} |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//config/webpack/environment.js | |
//requires you: yarn add worker-loader | |
var webpack = require('webpack'); | |
environment.plugins.append( | |
'Provide', | |
new webpack.ProvidePlugin({ | |
pdfjsLib: 'pdfjs-dist/es5/build/pdf', | |
pdfjsWorker: 'worker-loader?esModule=false&filename=[name].js!pdfjs-dist/es5/build/pdf.worker' | |
}) | |
) | |
module.exports = environment |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is my solution for rails/webpacker#2804 and mozilla/pdf.js#12786
Unfortunately pdf.js in its current form does not export correctly for webpacker, however, this gist will let you set up a globally scoped pdfjs lib. You also need to
yarn add worker-loader
and globally scope the worker-loader as exported from pdf.worker.Also, you must currently use the es5 version as compilation of the other will still fail with this strategy.
NOTE: I did NOT do anything like
require('pdfjs-dist/es5/build/pdf')
in my application.js and I did notimport
it in my module, because its a globally-scoped kludgearound!