Convert HTML to PDF in MVC with iTextSharp in MVC Razor

后端 未结 9 1273
情深已故
情深已故 2020-12-02 15:56

I am trying to convert HTML to PDF with iTextSharp in MVC Razor, but everything I have tried has not worked. Does anyone know how to accomplish this?

9条回答
  •  没有蜡笔的小新
    2020-12-02 16:43

    Here is a complete example for MVC Razor in C# using the evo html to pdf for .net to convert the current MVC view to PDF and send the resulted PDF to browser for download:

    [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;
    }
    

提交回复
热议问题