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

后端 未结 2 849
耶瑟儿~
耶瑟儿~ 2021-01-02 11:32

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

2条回答
  •  难免孤独
    2021-01-02 11:46

    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
    }
    

提交回复
热议问题