How can I exactly implement pdfjs in elixir liveview?
Please provide a practical example/guide
What have you tried so far? Have you got pdfjs working without liveview?
I have installed pdfjs using npm, I have made a template and created a hook in app.js.
At template
<div
id="pdfReader"
phx-hook="pdfReader"
phx-update="ignore">
</div>
<div id="pdfReader"></div>
<canvas id="myreader"></canvas>
At app.js
import Hooks from "./hooks";
At hooks.js
import pdfReader from "./hooks/pdf";
let Hooks = {
pdfReader: pdfReader
}
export default Hooks;
At pdf.js
import pdfjsLib from "pdfjs"
const pdfReader = nameRoute => {
let loadingTask = pdfjsLib.getDocument(nameRoute),
pdfDoc = null,
canvas = document.querySelector('#cnv'),
ctx = canvas.getContext('2d'),
scale = 1.5,
numPage = 1;
const GeneratePDF = numPage => {
pdfDoc.getPage(numPage).then(page => {
let viewport = page.getViewport({ scale: scale });
canvas.height = viewport.height;
canvas.width = viewport.width;
let renderContext = {
canvasContext : ctx,
viewport: viewport
}
page.render(renderContext);
})
document.querySelector('#npages').innerHTML = numPage;
}
loadingTask.promise.then(pdfDoc_ => {
pdfDoc = pdfDoc_;
document.querySelector('#npages').innerHTML = pdfDoc.numPages;
GeneratePDF(numPage)
});
}
const startPdf = () => {
pdfReader('../')
}
window.addEventListener('load', startPdf);
export default pdfReader;
But still no working
Anyone wishing to help might first want to look through this discussion of the same problem on the Elixir Discord to prevent double work and outdated code examples: Discord
Here’s a working example from my project:
To install JS dependency: npm install pdfjs-dist
JS:
- purple/pdf.js at master · knoebber/purple · GitHub
- purple/app.js at master · knoebber/purple · GitHub
LiveView:
It has simple pagination and zoom controls. It’s a bit hacky and the JS is messy but hopefully it can help others get started…