How to show a pdf file in the browser tab from an action method

前端 未结 2 1166
一生所求
一生所求 2021-01-16 11:26

I\'m trying to do pdf viewer functionality in mvc application. When user click the \"read the pdf\" link it should open a new tab/window and user should be able view the pdf

相关标签:
2条回答
  • 2021-01-16 11:52

    Show an anchor tag in your first view and pass an id (to identify what PDF to show)

    @Html.ActionLink("read the pdf","view","doc",new { @id=123},null)
    

    Now in the doc controller, have an action method which have a parameter called id and return the pdf there using the File method.

    public ActionResult View(int id)
    {
      byte[] byteArrayOfFile=GetFieInByteArrayFormatFromId(id);
      return File(byteArrayOfFile,"application/pdf");
    }
    

    Assuming GetFileInByteArrayFormatFromId is the method which returns the byte array format of the PDF file.

    You can also return the PDF if you know the full path to the PDF file physically stored, using this overload.

    public ActionResult Show()
    {
      string path="FullPAthTosomePDFfile.pdf";
      return File(path, "application/pdf","someFriendlyName.pdf");
    }
    

    Show the PDF in a browser without downloading it

    Based on the browser setting of the end user, the above solution will either ask user whether he/she wishes to download or open the file or simply download/open the file. If you prefer to show the file content directly in the browser without it gets downloaded to the user's computer, you may send a filestream to the browser.

    public ActionResult Show(int id)
    {
        // to do : Using the id passed in,build the path to your pdf file
    
        var pathToTheFile=Server.MapPath("~/Content/Downloads/sampleFile.pdf");
        var fileStream = new FileStream(pathToTheFile,
                                            FileMode.Open,
                                            FileAccess.Read
                                        );
        return  new FileStreamResult(fileStream, "application/pdf");           
    }
    

    The above code expects you to have a pdf file named sampleFile.pdf in ~/Content/Downloads/ location. If you store the file(s) with a different name/naming convention, you may update the code to build the unique file name/path from the Id passed in.

    0 讨论(0)
  • 2021-01-16 11:53

    If you want to display the PDF Content in browser, you can use iTextShare dll.

    Refer the link http://www.codeproject.com/Tips/387327/Convert-PDF-file-content-into-string-using-Csharp.

    Reading PDF content with itextsharp dll in VB.NET or C#

    0 讨论(0)
提交回复
热议问题