Niklas
Niklas

Reputation: 13135

Prevent ActionResult from posting to a new page?

My project is very similar to NerdDinner and I'm generating a pdf-document using PdfSharp.

In my view I'm using this:

<%: Html.ActionLink("Pdf", "GeneratePdf1", "Persons")%>

Calling this ActionResult:

    public ActionResult GeneratePdf1()
    {
        // Create a new PDF document
        PdfDocument document = new PdfDocument();
        document.Info.Title = "Created with PDFsharp";

        // Create an empty page
        PdfPage page = document.AddPage();

        // Get an XGraphics object for drawing
        XGraphics gfx = XGraphics.FromPdfPage(page);

        // Create a font
        XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic);

        // Draw the text
        gfx.DrawString("Hello, World!", font, XBrushes.Black,
        new XRect(0, 0, page.Width, page.Height),
        XStringFormats.Center);

        // Save the document...
        const string filename = "HelloWorld.pdf";
        document.Save(filename);
        Process.Start(filename);
        return View();
    }  

A few questions/problems on this:

Upvotes: 0

Views: 681

Answers (2)

DanielB
DanielB

Reputation: 20220

you should replace these lines:

Process.Start(filename);
return View();

with

return File(filename, "application/pdf");

You may also have a third param with the downloaded filename, if it should be different to the action name.

return File(filename, "application/pdf", "myGeneratedPdf.pdf");

Also be sure the filename is unique per request or use a MemoryStream like it is suggested by Chris Kooken.

Btw: Process.Start(filename) will run the file on the server machine. that may work on your development machine, but on a live server the pdf will open on the server!!!

Upvotes: 2

Chris Kooken
Chris Kooken

Reputation: 33870

You want to return a FileResult not an ActionResult. Also, I would save it to a MemoryStream and return the byte array, not use a file. Full solution below.

public FileResult GeneratePdf1()
{
    // Create a new PDF document
    PdfDocument document = new PdfDocument();
    document.Info.Title = "Created with PDFsharp";

    // Create an empty page
    PdfPage page = document.AddPage();

    // Get an XGraphics object for drawing
    XGraphics gfx = XGraphics.FromPdfPage(page);

    // Create a font
    XFont font = new XFont("Verdana", 20, XFontStyle.BoldItalic);

    // Draw the text
    gfx.DrawString("Hello, World!", font, XBrushes.Black,
    new XRect(0, 0, page.Width, page.Height),
    XStringFormats.Center);


    MemoryStream stream = new MemoryStream();
    document.Save(stream, false);

    return File(stream.ToArray(), "application/pdf");
}

Upvotes: 4

Related Questions