Home > other >  Display pdf file over 2MB using embed element
Display pdf file over 2MB using embed element

Time:09-05

I am making an application that brings up a preview of PDF files. Embedding with an embed element works well for small PDF files but fails for larger PDF files because of the size limits for data urls. I'm looking for a way to use the browser's native PDF viewer to view PDF files but without using data urls.

My code currently looks something like the following:

<script>
function addToCard(input) {
   if (input.files.length <= 0) return;
   let fileReader = new FileReader();
   fileReader.onload = async function () {
       pdfCard.src = fileReader.result;
   };
   fileReader.readAsDataURL(input.files[0]);
}
</script>

<input type=file oninput="addToCard(this)" />

<embed id=pdfCard style="width:100%;height:100%" />

Example. The original PDF is here.

CodePudding user response:

You could use URL.createObjectURL() on the PDF. It also creates a URL representing the object; however, the difference between an object URL and a data URL is that, while a data URL contains the object itself, an object URL is a reference to the object, which is stored in memory. This means that object URLs are significantly shorter than data URLs and take less time to create.

There are two drawbacks to this approach that may prevent you from using it. The first is that an object URL will only work on the page on which it was created. Attempting to use an object URL on a different page will not work. If you need to access this URL anywhere other than the page it was created on, this approach will not work.

The second is that object URLs keep the object for which they were created stored in memory. You have to revoke the object URL when you are done using it with the URL.revokeObjectURL() method, otherwise it will cause a memory leak. This means that you might have to add some extra code that revokes the object URL once the PDF is loaded. This example may be helpful.

The implementation might look something like this:

function addToCard(input) {
  if (input.files.length <= 0) return;

  pdfCard.src = URL.createObjectURL(input.files[0])

  // gonna have to call revokeObjectURL eventually...
}
  • Related