Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Open PDF in a new tab in browser

Never done this before so not sure what is involved in it. I did search and found many answers but they were more complex than what I need. For example they needed to zoom in, generate, create accurate thumbnail, embed the actual PDF in the webpage, etc... But my question is much simpler: If my guy that I am showing his information on webpage has some PDF to show I just want to put a generic PDF icon on the page, people click on it and the actual PDF opens in a new tab in their browser.

What is involved in just doing that? It is not like a file path, the PDF is saved in SQL server as binary objects or whatever it does to save it in SQL Server..it is not a file disk path on server

like image 676
Bohn Avatar asked May 26 '16 15:05

Bohn


2 Answers

Your tags indicate asp.net-mvc.

Create a controller to handle requests for the PDF file

Pseudo:

[RoutePrefix("Pdf")]
public class PdfController : Controller {
    [Route("{id}"]
    public ActionResult GetPDF(int id) {    
        //...Code to extract pdf from SQLServer and store in stream
        Stream stream = GetDataFromSQLServerById(id);
        return File(stream,"filename.pdf");
    }
}

On client

<a href="/Pdf/123456" target="_blank">
    <img src="images/pdficon.jpg">
</a>

Update:

Referencing @ChrisPratt's comment; (which I forgot to include in my answer)

The target attribute on the anchor tag is what will tell the browser to open the link in a new tab.

like image 148
Nkosi Avatar answered Nov 15 '22 07:11

Nkosi


Create a Controller action to for your link

public PdfResult GetPdf(int databaseRecordId)
{
    var dbRecord = your code to return the sql record.

    return new PdfResult(dbRecord.PdfBytes, "whatever name you want to show.pdf");

}

public class PdfResult : FileResult
{
    private const String DefaultFileName = "file.pdf";
    private readonly Byte[] _byteArray;

    public PdfResult(Byte[] byteArray, String fileName = DefaultFileName)
        : base(MediaTypeNames.Application.Pdf)
    {
        _byteArray = byteArray;
        FileDownloadName = fileName;
    }
    protected override void WriteFile(HttpResponseBase response) { response.BinaryWrite(_byteArray); }
}

view code

<a href="<controller/action/databaseRecordId>" target="_blank">
<img src="<image-path>">
</a>
like image 34
Fran Avatar answered Nov 15 '22 06:11

Fran