user1531040 user1531040 - 12 days ago 4x
C# Question

Duplicate headers and Calling the file in the wrong path

I'm trying to create and showing a pdf from my webpage by clicking a link. But when the system has to show it goes something wrong.

When I use this command

return new FileStreamResult(fileStream, "application/pdf");

It shows a empty pdf file:


It is saved as: C:\Apps\MyWebSolution\MyWeb\Documenten\MyList_198721%20.pdf

And when I use this command:

return File(fileStream, "application/pdf", fullFileName);

then I get an error message:


What am I doing wrong?

public FileStreamResult PDFGenerator(string html, string fileName)
string fullFileName = Server.MapPath("~/Documenten/" + fileName + ".pdf");
Stream fileStream = CreatePDF(html, fullFileName);

HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + fullFileName);

//return new FileStreamResult(fileStream, "application/pdf");
return File(fileStream, "application/pdf", fullFileName);

If I had to post more. I'll do it. But I don't think it is needed.


This is my result that works:

This is calling from the View

    public HttpResponseBase HitlijstNaarPdf(int? AID_Hitlijst = 0)
        var model = new HitlijstModel();

        string sHtmlInhoud = ViewRenderer.RenderView("Hitlijst", model, ControllerContext);
        string fileName = "Hitlijst_" + AID_Hitlijst.ToString() + ".pdf";

        return CreatePDF(sHtmlInhoud, fileName);

    private HttpResponseBase CreatePDF(string html, string fileName)
        string convertingTool = Server.MapPath("~/bin/wkhtmltopdf.exe ");

        ProcessStartInfo psi = new ProcessStartInfo(convertingTool);
        psi.UseShellExecute = false;
        psi.RedirectStandardOutput = true;
        psi.RedirectStandardInput = true;
        psi.RedirectStandardError = true;
        psi.CreateNoWindow = true;

        Process myProcess = Process.Start(psi);

        string fullFileName = Server.MapPath("~/Documenten/" + fileName);
        if (!System.IO.File.Exists(fullFileName))
            Document pdfDocument = new Document(PageSize.A4, 30, 30, 30, 30);

            PdfWriter writer = PdfWriter.GetInstance(pdfDocument, new FileStream(fullFileName, FileMode.Create));
            PdfWriter.GetInstance(pdfDocument, Response.OutputStream);

            XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDocument, new StringReader(html));

        WebClient client = new WebClient();
        Byte[] buffer = client.DownloadData(fullFileName); 
        Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
        Response.ContentType = "application/pdf";

        return Response;