Open PDF in a new tab in browser

2019-04-09 05:53发布

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

2条回答
ら.Afraid
2楼-- · 2019-04-09 06:29

Create a Controller action to for your link

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

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

}

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>
查看更多
▲ chillily
3楼-- · 2019-04-09 06:38

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.

查看更多
登录 后发表回答