Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Data URI Hash Parameters (Hide PDF toolbar for data URI)

Tags:

html

pdf

data-uri

I have a PDF base64 encode data URI.

eg:

return <object data="data:application/pdf;base64,JVBERi0xLjMKJf////8KOCAwIG9...VmCjI0MTU4OAolJUVPRgo=" type="application/pdf"></object>

I am able to embed it in the page without any problem. However, by default browsers include a toolbar in the PDF.

PDF toolbar example

It seems like the only way to disable this toolbar is to include some hash parameters at the end of the url.

eg.

<object data="path/to/file.pdf#toolbar=0&navpanes=0&scrollbar=0" type="application/pdf"></object>

Which works fine if the PDF is accessed through a relative path or URL, but I cant figure out a way to make this work with a data URI.

Is there any way to include these hash parameters at the end of a URI?

Or does anyone know some way to hide this toolbar some other way?

Any help is greatly appreciated. Thanks in advance. :)

like image 685
nmajor Avatar asked Feb 12 '16 20:02

nmajor


2 Answers

Like kolin said there is no way to directly send in query strings with a data URI. However, you can switch the data URI into a blob URL and pass the parameters in there.

Just take your base64 data and convert it into a pdf blob like so:

function b64toBlob(b64Data, contentType) {
var byteCharacters = atob(b64Data)

var byteArrays = []

for (let offset = 0; offset < byteCharacters.length; offset += 512) {
    var slice = byteCharacters.slice(offset, offset + 512),
        byteNumbers = new Array(slice.length)
    for (let i = 0; i < slice.length; i++) {
        byteNumbers[i] = slice.charCodeAt(i)
    }
    var byteArray = new Uint8Array(byteNumbers)

    byteArrays.push(byteArray)
}

var blob = new Blob(byteArrays, { type: contentType })
return blob}

Then use the createObjectURL method to create a URL you can put query strings on like so:

URL.createObjectURL(b64toBlob(data.buffer.data, 'application/pdf')) + '#toolbar=0&navpanes=0&scrollbar=0'

Set your object's data attribute to the resulting string and you'll have it.

like image 133
Sam-Graham Avatar answered Sep 25 '22 03:09

Sam-Graham


Yesterday I was also facing similar problem and found a working solution. When you are using base64 in URI and trying to set default behavior none(#toolbar=0&navpanes=0&scrollbar=0&), src is not able to detect the boundary starting with '#'. You can get wanted result with this instead data:application/pdf;#toolbar=0&navpanes=0&scrollbar=0&;base64,your_base64_string. As per your code you can return like this:

return <object data="data:application/pdf;#toolbar=0&navpanes=0&scrollbar=0&;base64,JVBERi0xLjMKJf////8KOCAwIG9...VmCjI0MTU4OAolJUVPRgo=" type="application/pdf"></object>

I hope this may help you and others.

like image 20
Ravi Avatar answered Sep 24 '22 03:09

Ravi