Convert HTML to PDF in ASP.NET MVC

前端 未结 8 689
陌清茗
陌清茗 2021-02-06 07:56

Im working in a project which requires current html page to convert in pdf and that pdf will automatically save on button click on server and its reference will be save in da

8条回答
  •  死守一世寂寞
    2021-02-06 08:15

    The C# code below can be used in a MVC application to convert the current view to PDF and produce a PDF in a buffer that can be saved on server or sent to browser for download. The code is using evopdf library for .net to perform the HTML to PDF conversion:

    [HttpPost]
    public ActionResult ConvertCurrentPageToPdf(FormCollection collection)
    {
        object model = null;
        ViewDataDictionary viewData = new ViewDataDictionary(model);
    
        // The string writer where to render the HTML code of the view
        StringWriter stringWriter = new StringWriter();
    
        // Render the Index view in a HTML string
        ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, "Index", null);
        ViewContext viewContext = new ViewContext(
                ControllerContext,
                viewResult.View,
                viewData,
                new TempDataDictionary(),
                stringWriter
                );
        viewResult.View.Render(viewContext, stringWriter);
    
        // Get the view HTML string
        string htmlToConvert = stringWriter.ToString();
    
        // Get the base URL
        String currentPageUrl = this.ControllerContext.HttpContext.Request.Url.AbsoluteUri;
        String baseUrl = currentPageUrl.Substring(0, currentPageUrl.Length - "Convert_Current_Page/ConvertCurrentPageToPdf".Length);
    
        // Create a HTML to PDF converter object with default settings
        HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();
    
        // Convert the HTML string to a PDF document in a memory buffer
        byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlToConvert, baseUrl);
    
        // Send the PDF file to browser
        FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");
        fileResult.FileDownloadName = "Convert_Current_Page.pdf";
    
        return fileResult;
    }
    

提交回复
热议问题