Reputation: 49
I'm working on a website where the users can solve a practice exam. My client wants to include a div next to the exam with a PDF viewer. The idea is that the user can select a PDF file from his local machine and it will be loaded into the PDF viewer next to the exam. I made it work using pdf.js and pdfobject. The problem is that both options require the PDF file to be uploaded to our server.
Due to intellectual property law, that is unacceptable to our client. They want the PDF file to be embeded without uploading it to our server. So it has to be loaded directly from the user's machine. I found that it can't be done. All the plugins I tried require a virtual url, and will not accept a physic one (file:///local/path/file.pdf).
I don't want to just tell my client "it can't be done". I would like to know a technical explanation of why can't it be done.
If somebody knows a way to make it work it would be better!
Upvotes: 0
Views: 1057
Reputation: 218847
You might be able to do this, if the browser supports it. Take a look at the FileReader object. If the user's browser supports that, you can allow the user to select a file and reference that file in code. Something like this works for me in Firefox:
$('input[type=file]').change(function () {
if (window.FileReader) {
var input = this;
if (input.files && input.files[0]) {
var reader = new FileReader();
reader.onload = function (e) {
$(input).next('iframe').attr('src', e.target.result);
}
reader.readAsDataURL(input.files[0]);
}
}
});
So if you have a input type="file"
followed by an iframe
then this will allow the user to select the file, and once it's selected it will load it into the iframe
as a base64-encoded data URI.
Example here.
Upvotes: 0
Reputation: 328614
Try to load it in a <iframe>
with the URL of the PDF as src
. But it might fail because of the client's browser's security policy. So this is brittle at best.
Maybe you can use HTML5 localstorage to upload the file to a "safe" location ("safe" as far as the browser is concerned).
PDFJS.getDocument()
supports "a typed array (Uint8Array)
already populated with data or parameter object." So upload to local storage, get the document as bytes from there and then pass it to pdf.js.
Related:
Upvotes: 0
Reputation: 943569
This is a security policy. Issues it defends against include:
- Allowing sites to detect your operating system by checking default installation paths
- Allowing sites to exploit system vulnerabilities (e.g., C:\con\con in Windows 95/98)
- Allowing sites to detect browser preferences or read sensitive data
Upvotes: 1