How to open pdf file in modal popup in ASP.NET C#

BeUnique 2,112 Reputation points
2024-06-04T18:32:27.64+00:00

I am developing ASP.NET application. i used gridview to insert, update and delete the data.

Also, i am uploading documents in file server path.

now, i am uploading all the documents as pdf and in past days i have uploaded document as image.

Now and future, i want to upload all the documents only in pdf.

How to open the pdf document in same modal popup window...?

Note : As a user friendly, i need scroll position as vertical in the modal popup to scroll down easily for end user

below is my code

 <script type='text/javascript'>
        function openModal() {
            $('[id*=PopModal]').modal('show');
        }
    </script>    
<div class="modal fade" id="PopModal" role="dialog">
        <div class="modal-dialog">
            <!-- Modal content-->
            <div class="modal-content">
                <div class="modal-header">
                    <button type="button" class="close" data-dismiss="modal">
                        &times;</button>
                    <h4 class="modal-title">Customer Details</h4>
                </div>
                <div class="modal-body">
                    <div class="col-lg-12 col-sm-12 col-md-12 col-xs-12">
                        <div class="form-group">
                        </div>
                        <div class="form-group">
                            <asp:Image ID="img" runat="server" Width="500px" Height="400px" />
                        </div>
                    </div>
                </div>
                <div class="modal-footer">
                    <asp:Button ID="btnDownload" runat="server" Text="Download" OnClick="DownloadFile"  />
                    <button type="button" data-dismiss="modal">Close</button>
                </div>
            </div>
</div>
<asp:TemplateField ItemStyle-HorizontalAlign="Center">
      <HeaderTemplate>
           Show File
      </HeaderTemplate>
      <ItemTemplate>
           <asp:LinkButton ID="lnkBtnEdit" runat="server" Text="Show" OnClick="Display"></asp:LinkButton>
          <asp:HiddenField ID="HiddenField1" runat="server" Value='<%# Eval("FilePath")%>' />
      </ItemTemplate>
</asp:TemplateField>
protected void Display(object sender, EventArgs e)
        {
            int rowIndex = Convert.ToInt32(((sender as LinkButton).NamingContainer as GridViewRow).RowIndex);
            GridViewRow row = grdBills.Rows[rowIndex];
            string FPath = (row.FindControl("HiddenField1") as HiddenField).Value; \\ pdf file
            string sMineType = MimeMapping.GetMimeMapping(FPath);
            if (!string.IsNullOrEmpty(FPath))
            {
                //check file exists in directory
                if (File.Exists(FPath))
                {
                    byte[] rawFile = File.ReadAllBytes(FPath);
                    img.ImageUrl =
                        $@"data:{sMineType};base64,{Convert.ToBase64String(rawFile)}";
                    ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
                }
            }
        }
ASP.NET
ASP.NET
A set of technologies in the .NET Framework for building web applications and XML web services.
3,474 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,887 questions
{count} votes

Accepted answer
  1. Lan Huang-MSFT 29,251 Reputation points Microsoft Vendor
    2024-06-05T05:27:03.84+00:00

    Hi @Gani_tpt,

    You can try using Literal control to view PDF files in browser.

    You can use the HTML OBJECT tag to embed PDF into the browser. Generate an HTML string of the OBJECT tag, in which the path of the PDF file is set. Then set the HTML string to the Literal tag.

    Details are as follows:

     <script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
     <script type="text/javascript" src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
     <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" />
     <script type='text/javascript'>
         function openModal() {
             $('[id*=PopModal]').modal('show');
         }
     </script>   
    
     <div class="modal fade" id="PopModal" role="dialog">
         <div class="modal-dialog">
             <!-- Modal content-->
             <div class="modal-content">
                 <div class="modal-header">
                     <button type="button" class="close" data-dismiss="modal">
                         &times;</button>
                     <h4 class="modal-title">Customer Details</h4>
                 </div>
                 <div class="modal-body">
                     <div class="col-lg-12 col-sm-12 col-md-12 col-xs-12">
                         <div class="form-group">
                         </div>
                         <div class="form-group">
                            <asp:Literal ID="ltEmbed" runat="server" />
                         </div>
                     </div>
                 </div>
                 <div class="modal-footer">
                     <asp:Button ID="btnDownload" runat="server" Text="Download" OnClick="DownloadFile" />
                     <button type="button" data-dismiss="modal">Close</button>
                 </div>
             </div>
         </div>
     </div>
    
     protected void Display(object sender, EventArgs e)
     {
         int rowIndex = Convert.ToInt32(((sender as LinkButton).NamingContainer as GridViewRow).RowIndex);
         GridViewRow row = gvCustomers.Rows[rowIndex];
         string FPath = (row.FindControl("HiddenField1") as HiddenField).Value;
         Session["FPath"] = FPath;
         if (!string.IsNullOrEmpty(FPath))
         {
             string embed = "<object data=\"{0}\" type=\"application/pdf\" width=\"500px\" height=\"300px\">";
             embed += "If you are unable to view file, you can download from <a href = \"{0}\">here</a>";
             embed += " or download <a target = \"_blank\" href = \"http://get.adobe.com/reader/\">Adobe PDF Reader</a> to view the file.";
             embed += "</object>";
             ltEmbed.Text = string.Format(embed, ResolveUrl(FPath));              
             ScriptManager.RegisterStartupScript(this, this.GetType(), "Pop", "openModal();", true);
         }
     }
     protected void DownloadFile(object sender, EventArgs e)
     {
         string FPath = Session["FPath"].ToString();
         Response.ContentType = "application/pdf";
         Response.AppendHeader("Content-Disposition", "attachment; filename=" + Path.GetFileName(FPath));
         Response.WriteFile(FPath);
         Response.End();
     }
    

    Best regards,
    Lan Huang


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

2 additional answers

Sort by: Most helpful
  1. AgaveJoe 28,131 Reputation points
    2024-06-05T12:20:33.5433333+00:00

    First, let's break down what you're asking. A model is HTML in the current page loaded in the browser. We can rephrase your question as how to display a PDF in the browser. First, the browser needs a PDF plugin. Do your clients have a PDF plugin for their browsers?

    If the clients have the plugin then displaying a PDF is simply knowing the path to the PDF. Then you can use an iFrame or Object within the modal HTML.

    <iframe src="/Content/Files/MyPdf.pdf"></iframe>
    
    

    I would create a simple test to verify the browser can display a PDF.

    If the PDF is stored in a database then write the standard generic handler in ASP.NET to fetch the file from the database and return a file stream. The src above will be the path to the generic handlers with whatever query parameters are needed to fetch the file from the database. This is a very common ASP.NET Web Forms problem which has been solved and well documented over the years. Do a Google search.

    https://yasserzaid.wordpress.com/2011/02/13/how-to-download-files-from-server-to-client-using-a-generic-handler/

    If you need a dynamic solution then try designing a solution using standard ASP.NET Web Forum controls on your own. If you are asking the community to design and write a dynamic solution then we need better requirements.

    we are using 3rd party pdf editor. the whole organization using the mentioned 3rd party pdf. will that affect for opening pdf...?

    We cannot read your mind and have no idea what 3rd party editor you are using. If your goal is to load the PDF in the browser, enter data in the PDF, then saves the data/PDF then I doubt the 3rd party editor has this capability. You'll need to reach out the 3rd party provider or read the provider's documentation to verify your use case is possible.

    The typical flow is the user downloads the PDF. The user enters data in the PDF fields. The user saves the PDF to their system. Finally, the user uploads the PDF using your Web Forms Application.


  2. AgaveJoe 28,131 Reputation points
    2024-06-06T14:00:11.34+00:00

    I tested with correct path. but, still pdf not loading in the modal popup.

    The user's browser cannot access a network share.

    If the web server has access to the network share then use a generic file handler to return a file steam. See my last post! Please make an effort to learn the basics...

    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.