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

二次信任 提交于 2019-11-30 13:46:16

I'm not familar with PDF sharp but for MVC is mostly done via built in functionality. You need to get your pdf document represented as an array of bytes. Then you'd simply use MVC's File method to return it to the browser and let it handle the download. Are there any methods on their class to do that?

public class PdfDocumentController : Controller
{
    public ActionResult GenerateReport(ReportPdfInput input)
    {
        //Get document as byte[]
        byte[] documentData;

        return File(documentData, "application/pdf");
    }

}

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
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!