Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Providing the Object tag with data directly

I wanted to embed a PDF file in my website, it looked like this:

<object data="data/PDFTest1.pdf" type="application/pdf" id="data"></object>

But then I wanted to first Get the file with ajax (in a javascript file), edit it's source code in JavaScript, and then create an <object> and give it the resulting data. The problem is that the Object needs a url in its data attribute, and does not accept the actual data directly. How can I handle this?

Is there a way to create a "fake url" in javascript for example?

Or can I somehow pass the data in another way to the object?

Or should I maybe use some other tag ?

Thanks in advance and sorry for my English.

like image 336
H. Saleh Avatar asked Apr 05 '17 15:04

H. Saleh


2 Answers

You don't actually need a URL. You can convert the PDF to base64 and set the data attribute to the data itself. You just need to prefix the base64 with "data:" then the mime type, a semi-colon, "base64," and then the base64 encoded string that represents the PDF.

<object data="data:application/pdf;base64,YOURBASE64DATA" type="application/pdf"></object>
like image 103
joelgeraci Avatar answered Oct 14 '22 21:10

joelgeraci


I know this is a bit old, but I wanted to expand on the selected answer with how to generate the data url using FileReader.readAsDataURL.

Here's an example wrapped in a Promise.

export function blobAsDataUrl (blob) {
  return new Promise((resolve, reject) => {
    let reader = new FileReader();

    reader.onload = (event) => {
      resolve(event.target.result);
    };
    reader.onerror = (error) => {
      reader.abort();
      reject(error);
    };

    reader.readAsDataURL(blob);
  });
}

// Handle the promise however you like
// This is in the format: data:application/pdf;base64,BASE64DATA
let data_url_for_object = await blobAsDataUrl(<Blob or File>);

https://developer.mozilla.org/en-US/docs/Web/API/FileReader

like image 37
ralphpig Avatar answered Oct 14 '22 21:10

ralphpig