DEV Community

David Lopez
David Lopez

Posted on

How to Load a PDF in a Browser from a PDF Byte Array

I got stuck on this seemingly easy task. I've somehow had gone my whole career without having to do this, but I've seen it done countless times on other sites.

I think the reason why I got stuck was because I tried the most complex solutions first thinking that they're more likely to work. I was wrong. Lesson learned. Try the easiest solution first.

Here's my solution. I ended up using an embed tag and make the src attribute equal to the api endpoint that was returning the byte array.

<div class="pdf">
  <embed src="https://api_url/path/to/endpoint" type="application/pdf" />
</div>

Your last step would be to style it however you want and configure the PDF.

Configuring the PDF

After you get the PDF loading, you may also be wondering how to size the PDF to fit in the <embed> tag.

The problem is that your PDF may not always fit beautifully in the browser window when it loads. Maybe it's really small or it's too large. This article is how to fix that.

There are specific types of query parameters for interacting with a PDF in the browser. You use these to help format the PDF. They look like this:

filename.pdf#view=FitH

And in the case where we're using the <embed> tag:

<embed src="https://api_url/path/to/endpoint#view=FitH" type="application/pdf" />

Instead of the parameters starting with a '?', it will start with a '#'. The '#' and everything after is called a fragment. Fragments don't get sent to the server during an HTTP request.

The keys and values in the fragment will tell the browser how to size the PDF. Follow the link below for a list of possible keys and values to use.

https://www.adobe.com/content/dam/acom/en/devnet/acrobat/pdfs/pdf_open_parameters.pdf

I wanted the PDF page to fit on the page and using this fragment, #view=FitV, solved my problem.

You may think it's strange that your typing in these keys and values into Chrome but they come from an Adobe document. Me too. I think it's because Chrome tried to use Adobe's system but I couldn't find any information about it from Google. All keys and values may not be properly documented or map over into Chrome. You'll have to test them out for now. If you find any better documentation, please let me know.

Now go ahead and try a few of these PDF query parameter fragments on your own PDF.

Top comments (1)

Collapse
 
sandeep2244 profile image
Sandeep Gadhiya

Hey David , Nice article.

What if we render pdf as editable and i want to capture that pdf with inputtext in byte array.