Search code examples
javascriptpdf.js

How to validate is pdf file password protected or not with pdf.js library?


How to validate is pdf file password protected or not with pdf.js library?

let input = document.querySelector("input");
    input.addEventListener('change',(e)=>{
        if(input.files[0].type=="application/pdf"){
            let fr = new FileReader();
        fr.onload=e=>{
            let res = fr.result;
            // i want to check here if selected pdf file is password protected or not
           pdfjsLib.getDocument(res).promise.then(pdf=>{
            let pages = pdf.numPages;
            console.log(pdf);
           })
            
        }
        fr.readAsArrayBuffer(input.files[0])
        }else{
            alert("Please Upload Valid PDF File")
        }
    })

Solution

  • You could try using onPassword:

    const pdfFile = pdfjsLib.getDocument(res);
    pdfFile.onPassword = (callback, reason) => {
        if (reason == 1) {
            // File is password protected
        }
    };