1 year ago

#364188

test-img

h3ckphy

Blurred pdf with pdf.js library

I'm using pdf.js library to render my pdf file on canvas. First I was searching a solution for rendering pdf with the size of canvas parent element. I've found it and it works fine. Then I solve the problem of rendering ALL pages at once. Finally, my code now looks this way:

pdfjsLib.GlobalWorkerOptions.workerSrc = `//cdnjs.cloudflare.com/ajax/libs/pdf.js/${pdfjsLib.version}/pdf.worker.min.js`;


class PdfLoader {
    currPage = 1;
    numPages = -1;
    doc = null;

    constructor($container) {
        this.$container = $container;
    }

    load(path) {
        // reset when using more than once
        this.currPage = 1;
        this.promise = new Promise(resolve => this.promiseResolve = resolve);
        this.$container.innerHTML = "";

        pdfjsLib.getDocument(path).promise.then(pdf => {
            this.doc = pdf;
            this.numPages = pdf.numPages;

            pdf.getPage(1).then(this._handlePage.bind(this));
        });

        return this;
    }

    _handlePage(page) {
        let viewport = page.getViewport({scale: 1});
        const scale = this.$container.clientWidth/viewport.width;
        // const outputScale = window.devicePixelRatio || 1;
        const outputScale = 1;

        viewport = page.getViewport({scale});

        const cnv = document.createElement("canvas");
        const ctx = cnv.getContext("2d");

        const width = Math.floor(viewport.width);
        const height = Math.floor(viewport.height);

        cnv.width = Math.floor(width * outputScale);
        cnv.height = Math.floor(height * outputScale);
        cnv.style.width = `${width}px`;
        cnv.style.height =  `${height}px`;

        const transform = (outputScale !== 1) ? [outputScale, 0, 0, outputScale, 0, 0] : null;

        page.render({
            canvasContext: ctx,
            transform: transform,
            viewport: viewport,
        });

        this.$container.appendChild(cnv);

        this.currPage++;
        if (this.doc !== null && this.currPage <= this.numPages) {
            this.doc.getPage(this.currPage).then(this._handlePage.bind(this));
        } else {
            this.promiseResolve();
        }
    }
}

const $pages = document.getElementById("pages");
const pdfLoader = new PdfLoader($pages);
pdfLoader.load("extendedReport.pdf").promise
    .then(initReport);


let arrow = null;

function initReport() {
  // my other stuff
}

And now my problem is that when viewing rendered pdf it looks like its quality is very low and text is blurred so the document is unreadable on mobile devices. I tried to change passed scale like they say on the internet, but that's not it. Could you help me, plz? What am I missing?

low quality of pdf

javascript

pdf

pdf.js

0 Answers

Your Answer

Accepted video resources