Skip to content

Instantly share code, notes, and snippets.

@Genkilabs
Created February 18, 2021 22:39
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Genkilabs/a5285020ca548f589b9c46497afca941 to your computer and use it in GitHub Desktop.
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
//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);
}
//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
@Genkilabs
Copy link
Author

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 not import it in my module, because its a globally-scoped kludgearound!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment