16

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.

anastaciu
  • 23,467
  • 7
  • 28
  • 53
H. Saleh
  • 554
  • 1
  • 5
  • 19

2 Answers2

30

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>
joelgeraci
  • 4,606
  • 1
  • 12
  • 19
8

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

ralphpig
  • 99
  • 2
  • 3