How do I display a PDF using PdfSharp in ASP.Net MVC?

Kevin picture Kevin · Feb 27, 2013 · Viewed 19.2k times · Source

We're making an ASP.Net MVC app that needs to be able to generate a PDF and display it to the screen or save it somewhere easy for the user to access. We're using PdfSharp to generate the document. Once it's finished, how do we let the user save the document or open it up in a reader? I'm especially confused because the PDF is generated server-side but we want it to show up client-side.


Here is the MVC controller to create the report that we have written so far:

public class ReportController : ApiController
{
    private static readonly string filename = "report.pdf";

    [HttpGet]
    public void GenerateReport()
    {
        ReportPdfInput input = new ReportPdfInput()
        {
            //Empty for now
        };

        var manager = new ReportPdfManagerFactory().GetReportPdfManager();
        var documentRenderer = manager.GenerateReport(input);
        documentRenderer.PdfDocument.Save(filename); //Returns a PdfDocumentRenderer
        Process.Start(filename);
    }
}

When this runs, I get an UnauthorizedAccessException at documentRenderer.PdfDocument.Save(filename); that says, Access to the path 'C:\Program Files (x86)\Common Files\Microsoft Shared\DevServer\10.0\report.pdf' is denied. I'm also not sure what will happen when the line Process.Start(filename); is executed.

This is the code in manager.GenerateReport(input):

public class ReportPdfManager : IReportPdfManager
{
    public PdfDocumentRenderer GenerateReport(ReportPdfInput input)
    {
        var document = CreateDocument(input);
        var renderer = new PdfDocumentRenderer(true, PdfSharp.Pdf.PdfFontEmbedding.Always);
        renderer.Document = document;
        renderer.RenderDocument();

        return renderer;
    }

    private Document CreateDocument(ReportPdfInput input)
    {
        //Put content into the document
    }
}

Answer

Kevin picture Kevin · Feb 28, 2013

Using Yarx's suggestion and PDFsharp Team's tutorial, this is the code we ended up with:

Controller:

[HttpGet]
public ActionResult GenerateReport(ReportPdfInput input)
{
    using (MemoryStream stream = new MemoryStream())
    {
        var manager = new ReportPdfManagerFactory().GetReportPdfManager();
        var document = manager.GenerateReport(input);
        document.Save(stream, false);
        return File(stream.ToArray(), "application/pdf");
    }
}

ReportPdfManager:

public PdfDocument GenerateReport(ReportPdfInput input)
{
    var document = CreateDocument(input);
    var renderer = new PdfDocumentRenderer(true,
        PdfSharp.Pdf.PdfFontEmbedding.Always);
    renderer.Document = document;
    renderer.RenderDocument();

    return renderer.PdfDocument;
}

private Document CreateDocument(ReportPdfInput input)
{
    //Creates a Document and puts content into it
}