2

I have a link on click on it an HTML page will be converted to PDF document then return this PDF file to the user.

HTML code:

<li><a href='@Url.Action("GetHTMLPageAsPDF", "Transaction", new { empID = employee.emplID })'>ViewReceipt</a></li>

Code behind:

public FileResult GetHTMLPageAsPDF(long empID)
{
    string htmlPagePath = "anypath...";
    // convert html page to pdf
    PageToPDF obj_PageToPDF = new PageToPDF();
    byte[] databytes = obj_PageToPDF.ConvertURLToPDF(htmlPagePath);

    // return resulted pdf document
    FileResult fileResult = new FileContentResult(databytes, "application/pdf");
    fileResult.FileDownloadName = empID + ".pdf";
    return fileResult;
}

The problem is when this file returned its downloaded to the user computer directly, I want to display this PDF file to the user then if he wants he can download it.

How can I do this?

Nkosi
  • 235,767
  • 35
  • 427
  • 472
Noor Allan
  • 421
  • 2
  • 7
  • 17

1 Answers1

6

You have to set the Content-Disposition header on the response to inline

public FileResult GetHTMLPageAsPDF(long empID) {
    string htmlPagePath = "anypath...";
    // convert html page to pdf
    PageToPDF obj_PageToPDF = new PageToPDF();
    byte[] databytes = obj_PageToPDF.ConvertURLToPDF(htmlPagePath);

    //return resulted pdf document        
    var contentLength = databytes.Length;      
    Response.AppendHeader("Content-Length", contentLength.ToString());
    //Content-Disposition header set to inline along with file name for download
    Response.AppendHeader("Content-Disposition", "inline; filename=" + empID + ".pdf");
       
    return File(databytes, "application/pdf;");
}

The browser will interpret the headers and display the file directly in the browser provided it has the capability to do so, either built in or via plugin.

Nkosi
  • 235,767
  • 35
  • 427
  • 472