How to Open .pdf on a new Tab
Asked Answered
I

9

25

The Objective:

I have to print a PDF on a new tab after some tasks have finished correctly.

Steps: I want to execute a method that should go to the server, take the PDF and open it on a new Tab, I was trying with these but is not working:

Controller: Export

 public ActionResult PrintPdf()
    {
        Response.AppendHeader("Content-Disposition", "inline; filename= " + MyClassPdfWriter.GetFileName);
        return File(MyClassPdfWriter.GetMemoryStream, "application/pdf");
    }

View:

function TasksSucced(){
      $.get('@Url.Action("PrintPdf", "Export", "new {target = _blank}")');
}
Indehiscent answered 11/4, 2013 at 8:39 Comment(3)
maybe it works but.. that's a little bit dirty.. jeje I'm gonna take a look if there's a better choice, if not I will use for sure your option :DIndehiscent
yes actually it is a dirty hack. :D Let me also know if you find anything better. :)Jose
Raman Ty!! I have found it! :)Indehiscent
I
37

Solved! That works for me

 window.open('/Export/PrintPdf');
Indehiscent answered 11/4, 2013 at 10:7 Comment(3)
The popup blocker is preventing the pdf from downloading in chrome, is there a way to circunvent it? (telling user to allow pop up for this page is beyond their comprehension :/Pontonier
Does not work for base64 encoded files. At least in Chrome.Tartlet
@Pontonier you can circumvent the popup blocker by only opening the tab in response to a user action. In other words, have them click a button to open it. So have a button that directly calls window.open().Eviaevict
F
14

There several ways to download or view the PDF.

  • View

You can set the content-type as application/pdf in the response header just like Content-Type: application/pdf

And in order to open it to new tab in javascript, please add this code.

window.open("Here Download PDF url", '_blank');
  • Download

You need to set the content-type as application/octet-stream in the response header just like application/octet-stream.

And add download HTML5 attribute to a tag or just target="_blank".

<a href="PDF URL" download="pdf">Download</a>
<a href="PDF URL" target="_blank">Download</a>

So you can use PDF.js or 3rd library to view the PDF in iFrame or inline page.

Fussbudget answered 12/6, 2019 at 22:27 Comment(0)
S
5
$("a[target!='_blank'][href$='.pdf']").attr("target", "_blank");
Staffordshire answered 3/12, 2014 at 12:14 Comment(2)
Exaclty what I needed :-) ThxHeartily
@Mepps Great! Glad I could help :)Staffordshire
G
4

If anyone is having a similar problem, none of the above solutions worked for me in Google Chrome (they did work in Firefox)

This code worked in all major browsers:

var a = document.createElement('A');
var filePath = 'https://pathtopdf.com/file.pdf';
a.href = filePath;
a.download = filePath.substr(filePath.lastIndexOf('/') + 1);
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
Groundsill answered 6/2, 2018 at 19:3 Comment(2)
Does not work for base64 encoded files. At least in Chrome.Tartlet
That downloads the file instead of opening it in a new tab as per question.Tartlet
M
0

You can try using jQuery.deffered. I prepared sample function for you. It will process getPdf call, and then will resolve promise. Hope this helps

function getPDF() {
    return '';
}

getPdf()
  .then(function(response) {
    console.log('response here' + response);
    window.open(response);
  }).fail(function(){
      console.error('failed reposne');
  });
Meltage answered 20/11, 2018 at 8:24 Comment(0)
J
0

https://stackoverflow.com/a/72527783

It's work me.

My sample code

    var order_id = $(this).data('order_id');

    var url = 'pdf url';

    var data      = {
        order_id
    };

    var myHeaders = new Headers();
    myHeaders.append("Content-Type", "application/x-www-form-urlencoded");

    var urlencoded = new URLSearchParams();
    urlencoded.append("param", JSON.stringify(data));

    var requestOptions = {
        method  : 'POST',
        headers : myHeaders,
        body    : urlencoded,
        redirect: 'follow'
    };

    fetch(url, requestOptions)
    .then((response) => response.blob())
    .then((blob) => {
        const _url = window.URL.createObjectURL(blob);
        window.open(_url, '_blank');
    }).catch((err) => {
        console.log(err);
    });
Jackleg answered 1/2, 2023 at 9:53 Comment(0)
H
0
const openPDF = (link: string) => {
    window.open(link, '_blank');
  };

Just use this simple and easy method

Hitchhike answered 23/5, 2023 at 10:42 Comment(1)
Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.Disgorge
S
0

Since window.open will not work properly because of browser's policy, you can do it next way.

If you have file URL, you can first fetch it, then convert response.body to uint8array, then create blob and open blob in browser. PDF in this case will be opened in a new tab.

const res = await fetch(url)
const uint8arr = new Uint8Array(await new Response(res.body).arrayBuffer())

const link = document.createElement('a')
const blob = new Blob([uint8arr], { type: 'application/pdf' })

link.href = window.URL.createObjectURL(blob)
link.setAttribute('download', 'file.pdf')

document.body.appendChild(link)

link.click()
Stelle answered 22/2 at 14:44 Comment(0)
S
-1

You can use the following solution

   jQuery('<form target="_blank" action="' + URL + '" method="get"></form>').appendTo('body').submit().remove();

where URL is the pdf url...

Saiff answered 25/3, 2017 at 23:54 Comment(1)
Does not work for base64 encoded files. At least in Chrome.Tartlet

© 2022 - 2024 — McMap. All rights reserved.