简体   繁体   中英

Customizing pdf.js

i would like to use pdf.js in my webApplication and customize it's view, so i can embedd it into the rest of my application (i was thinking about using an iframe).

At first i would like to get rid of most of the default toolbar-buttons like "print" or "download file" but keep the zoom and page navigation. Instead, i want these features (print/download) to appear inside my application's toolbar. How to do that? How can i hide the print/download buttons from the pdf.js toolbar and call this features with my custom buttons which are rendered inside my webapplication already?

Or should i use another library other than pdf.js?

Any information are very helpful!!

Ok, i found how to do it. To hide a button simply add the CSS class "hidden" to it like "toolbarButton download hiddenMediumView hidden". To download the file, just call "PDFViewerApplication.download();". To print it, use window.print().

All the handlers are listet in the view.js file. Just search for "// Event handling functions.". In my version it's on line 1840.

I guess that's the simplest way. Of cours buttons could be removed completely from the DOM but that would mean to also alter the view.js file.

you can also build your own pdf viewer.You need to add a canvas element in your document.See the sample code below.you can add simple buttons or screen swipes to navigate to next pages or reload with page with a different scale. Initially its set to fit the screen width. Also see examples from pdf.js github . Sample code:

    function initializePsfJS() {
    pdfDoc = null;
    pageNum = 1;
    pageRendering = false;
    pageNumPending = null;
    scale = 1;
    canvas = document.getElementById('the-canvas');
    ctx = canvas.getContext('2d');
    viewport = null;
    PDFJS.workerSrc = './js/pdf.worker.js';
}

/**
 * Get page info from document, resize canvas accordingly, and render page.
 * @param num Page number.
 */
function renderPage(num) {
    pageRendering = true;
    // Using promise to fetch the page
    pdfDoc.getPage(num).then(function (page) {
        if (scale === "fit") {
            var unscaledViewport = page.getViewport(1);
            var viewerCont = document.getElementById('viewerDiv');
            var bdrec = viewerCont.getBoundingClientRect();
            scale = Math.min((bdrec.height / unscaledViewport.height), (bdrec.width / unscaledViewport.width));
        }
        viewport = page.getViewport(scale);
        canvas.height = viewport.height;
        canvas.width = viewport.width;

        // Render PDF page into canvas context
        var renderContext = {
            canvasContext : ctx,
            viewport : viewport
        };
        var renderTask = page.render(renderContext);

        // Wait for rendering to finish
        renderTask.promise.then(function () {
            pageRendering = false;
            if (pageNumPending !== null) {
                // New page rendering is pending
                renderPage(pageNumPending);
                pageNumPending = null;
            }
            calculateinitialXY();
        });
    });
}

/**
 * If another page rendering in progress, waits until the rendering is
 * finised. Otherwise, executes rendering immediately.
 */
function queueRenderPage(num) {
    if (pageRendering) {
        pageNumPending = num;
    } else {
        renderPage(num);
    }
}

function getDocumentByXMLHttpRequest() {
    //reason for this
    //http://stackoverflow.com/questions/36199155/pdf-file-generated-by-post-request-not-opening
    var header = getHeader();
    var requesturl =  < url rest service url to fetch document >
        var xhr = new XMLHttpRequest();
    xhr.open('GET', requesturl);
    xhr.setRequestHeader(header.key, header.value);
    xhr.responseType = 'arraybuffer';
    xhr.onload = function () {
        if (this.status == 200) {
            onloadDocumentFromContent(this.response);
        } else {
            navigator.notification.alert('Error while requesting pdf with id ' + getDocumentId());

        }
    };
    xhr.send();
}
function onloadDocumentFromContent(pdfraw) {

    var docInitParams = {
        data : pdfraw
    };

    PDFJS.getDocument(docInitParams).then(function (pdfDoc_) {
        pdfDoc = pdfDoc_;

        // Initial/first page rendering

        renderPage(pageNum);
    });

}

If you are using pdfjs web version and you want to hide the print button for example you can do something like this:

 <iframe
        src={`/pdfjs/web/viewer.html?file=${pdfFile}`}
        onLoad={(e) => {
               Array.from(e.target.contentDocument
                    .getElementsByClassName('print'))
                    .forEach((i) => { i.classList.add('hidden'); });
                }}
            >
 </iframe>

You need to add the style to the new HTML rendered by iframe, by default the browser does not apply the styles from your main app to the iframe rendered app.

Another example could be adding simple color change:

 <iframe id='iframe_pdfjs'
    src={`/pdfjs/web/viewer.html?file=${pdfFile}`}
    onLoad={(e) => {
           const cssStyle = document.createElement('style');
           cssStyle.innerHTML = 'div {color: red;}';
    document.getElementsById('iframe_pdfjs').contentDocument.head.appendChild(cssStyle)
        ></iframe>

In the above example we are simply adding style tag to the iframe rendered HTML

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM