Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decrypt PDF file on client side and view with pdf.js

I'm working on a project that all pdf files are encrypted on Web Server.

With XMLHttpRequest I get content of the encrypted pdf file. Then with JavaScript tools I decrypt the file. After all assign the content of file to a javascript variable as decrypted_file. All this is done at client side.

Here is what i want to do;

pdf.js renders and views pdf file that is located on web server or the same directory base.

How could I handle pdf.js to get content from javascript variable not url as "http//yourdomain.com/first-test.pdf or file as "first-test.pdf"?

Any answers are welcome, thank you.

like image 876
akikara Avatar asked Jan 30 '15 18:01

akikara


People also ask

How do you check if a PDF is password protected or not JavaScript?

try { InputStream fis = new ByteArrayInputStream(pdfBytes); PDDocument doc = PDDocument. load(fis); if(doc. isEncrypted()) { //Then the pdf file is encrypeted. } }


1 Answers

Assuming that you are using the viewer.html of PDF.js, opening a PDF file from data is as easy as calling PDFViewerApplication.open with the right parameters.

Example: Typed arrays (Uint8Array / ArrayBuffer / ..)

// in viewer.html
var data = new Uint8Array( /* ... data ... */ );
PDFViewerApplication.open(data);

Example: Blob / File objects

// in viewer.html
var data = new Blob([ '%PDF....'] , {type: 'application/pdf'});
var url = URL.createObjectURL(data);
PDFViewerApplication.open(url);

Example: data URL (if supported by browser)

var url = 'data:application/pdf;base64,....';
PDFViewerApplication.open(url);

Example: data URL (any browser)

This consists of two steps: Decoding the base64 data-URL, and then converting the binary string to an Uint8Array.

var url = 'data:application/pdf;base64,....';
var data = url.split(';base64,')[1];
// Decode base64
var binaryString = atob(data);
// Convert binary string to Uint8Array
data = new Uint8Array(binaryString.length);
for (var i = 0, ii = binaryString.length; i < ii; ++i) {
    data[i] = binaryString.charCodeAt(i);
}
PDFViewerApplication.open(data);

Example: Using PDF.js in a frame

<iframe src="viewer.html" id="pdfjsframe"></iframe>
<script>
var pdfjsframe = document.getElementById('pdfjsframe');
// At the very least, wait until the frame is ready, e.g via onload.
pdfjsframe.onload = function() {
    var data = ... data here or elsewhere ... ;
    pdfjsframe.contentWindow.PDFViewerApplication.open(data);
};
</script>
like image 93
Rob W Avatar answered Sep 26 '22 14:09

Rob W