-1

I thought this would be simple, but I've been stuck for a while now. I'm trying to create a link that serves a PDF file in a new tab. Ideally, the PDF will open in a new tab (i.e. not download). For clarity, I'm not trying to convert HTML to a PDF - I already have the PDF created and saved.

For reference, this is what I'm trying to accomplish.

This is sample text in my .ejs file. I want to open myPDF in a new tab.

I checked this and this SO post, but that didn't work for me. The part that's throwing me off is serving the PDF file from a link.

Update
I'm adding more detail here. In the interim, I made some progress.

I'm able to have the PDF downloaded when the user goes to the specified URL. However, how do I have the PDF open in a new tab, rather than being automatically downloaded?

here is the code I'm using:

router.get('/test', (req, res) => {
    //res.send('success');
    console.log(__dirname);
    var file = fs.createReadStream('./public/Literature/table1.pdf');
    var stat = fs.statSync('./public/Literature/table1.pdf');
    res.setHeader('Content-Length', stat.size);
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', 'attachment; filename=table1.pdf');
    file.pipe(res);
});

Thanks.

shredGnar
  • 149
  • 2
  • 11

1 Answers1

0

I found an answer to my question, posting it here for anyone else.

To download a PDF, the following works which is pulled from this SO post.

    var file = fs.createReadStream('./public/Literature/table1.pdf');
    var stat = fs.statSync('./public/Literature/table1.pdf');
    res.setHeader('Content-Length', stat.size);
    res.setHeader('Content-Type', 'application/pdf');
    res.setHeader('Content-Disposition', 'attachment; filename=table1.pdf');
    file.pipe(res);

To open a PDF in a new tab, the second answer works in the same SO post.

    var data = fs.readFileSync('./public/Literature/table1.pdf');
    res.contentType('application/pdf');
    res.send(data);

This code was not working for me earlier due to an unrelated routing issue. Rookie errors are painful.

shredGnar
  • 149
  • 2
  • 11