简体   繁体   中英

Display pdf file over 2MB using embed element

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 .

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)

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM