Convert HTML to PDF in ASP.NET MVC

前端 未结 8 687
陌清茗
陌清茗 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:11

    use ABCpdf dll, here in text area we can write html code and on a button click corresponding pdf will be shown.ABCpdf trail version is easily available for downloding, adding linlk to download the ABCpdf dll https://www.websupergoo.com/download.htm

    index.cshtml

          @using (Html.BeginForm("covertopdf", "simple", FormMethod.Post))
    {
            <p style="margin-top:50px">
                Input Html: @Html.TextArea("Htmlcontent", new { @class = "form-control",@cols="160" , @rows="20"})<br />
                <input type="submit" class="btn-primary" value="Convertopdf" />
            </p>
    }
    

    SimpleController.cs

     public class SimpleController : Controller
        {
            public class FileViewModel
            {
                public byte[] Content { get; set; }
                public string Extension { get; set; }
                public string FileName { get; set; }
            }
    
           [HttpPost]
           [ValidateInput(false)]
           public FileStreamResult covertopdf(string Htmlcontent)
            //public FileStreamResult covertopdf(file fo)
            {
                var result = ExecuteAction(() =>
                {
                    var fileViewmodel = new FileViewModel
                    {
                        Content = ConvertHtmlToPdf(Htmlcontent),
                        //Content= ConvertHtmlToPdf(fo.cont),
                        Extension = "application/pdf",
                        FileName = "Policy Information.pdf"
                    };
                    return fileViewmodel;
                }, "covertopdf");
                // return result;
                HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);
                // Content is the file 
                Stream stream = new MemoryStream(result.Content);
                return new FileStreamResult(stream, "application/pdf")
                {
    
                };
            }
    
    
    
            public T ExecuteAction<T>(Func<T> action, string method)
            {
                try
                {
                    return action.Invoke();
                }
                catch (Exception ex)
                {
                    return default(T);
                }
            }
    
    
    
            protected byte[] ConvertHtmlToPdf(string html, string header = null, string footer = null, bool isPageNumberInFooter = false)
            {
                // Create ABCpdf Doc object
                var doc = new Doc();
                if (header == null && footer == null)
                    doc.Rect.Inset(20, 20);
                else
                    doc.Rect.String = "0 70 600 760"; /*padding from left, padding from bottom, width from left, height from bottom*/
                // Add html to Doc   
                //html = "<html><head></head><body></body></html>";
                int theId = doc.AddImageHtml(html);
    
                // Loop through document to create multi-page PDF
                while (true)
                {
                    if (!doc.Chainable(theId))
                        break;
                    doc.Page = doc.AddPage();
                    theId = doc.AddImageToChain(theId);
                }
                var count = doc.PageCount;
    
                /*****************Footer area******************/
                if (footer != null)
                {
                    var newfooter = "";
                    doc.Rect.String = "40 20 580 50";
                    for (int i = 1; i <= count; i++)
                    {
    
                        doc.PageNumber = i;
                        if (isPageNumberInFooter)
                        {
                            newfooter = footer.Replace("PageNumber", "Page " + i.ToString() + " of " + count.ToString());
                            int id = doc.AddImageHtml(newfooter);
    
                            while (true)
                            {
                                if (!doc.Chainable(id))
                                    break;
                                id = doc.AddImageToChain(id);
                            }
                        }
                        else
                            doc.AddText(footer);
                    }
                }
                /*****************Footer area******************/
    
    
                // Flatten the PDF
                for (int i = 1; i <= doc.PageCount; i++)
                {
                    doc.PageNumber = i;
                    doc.Flatten();
                }
    
                var pdf = doc.GetData();
                doc.Clear();
                // Get PDF as byte array. Couls also use .Save() to save to disk
                return pdf;
            }
        }
    
    0 讨论(0)
  • 2021-02-06 08:13

    In short:

    HTML Renderer for PDF using PdfSharp

        public static Byte[] PdfSharpConvert(String html)
        {
            Byte[] res = null;
            using (MemoryStream ms = new MemoryStream())
            {
                var pdf = TheArtOfDev.HtmlRenderer.PdfSharp.PdfGenerator.GeneratePdf(html, PdfSharp.PageSize.A4);
                pdf.Save(ms);
                res = ms.ToArray();
            }
            return res;
        }
    

    More Detailed Answer

    0 讨论(0)
  • 2021-02-06 08:14

    There is special nuget package RazorPDF. It simple works. RazorPDF site

    0 讨论(0)
  • 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;
    }
    
    0 讨论(0)
  • 2021-02-06 08:20

    I used iDiTect.Converter to convert html to pdf in asp.net mvc https://www.iditect.com/tutorial/html-to-pdf/, however it's not free code in short

    public static Byte[] ConvertToBytes()
    {
    HtmlToPdfConverter converter = new HtmlToPdfConverter();
    
    converter.DefaultStyleSheet = ".para{font-size: 24px; color: #FF0000;}";
    
    string htmlContent = "<p class=\"para\">Content with special style.</p><p>Content without style</p>";
    converter.Load(htmlContent);
    
    return converter.SaveAsBytes();
    }
    
    0 讨论(0)
  • 2021-02-06 08:27

    There are a number of html to pdf converters for .NET available out there. I can recommend ExpertPdf (www.html-to-pdf.net).

    Code looks something like this:

    PdfConverter pdfConverter = new PdfConverter();
    
    pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
    byte[] downloadBytes = pdfConverter.GetPdfFromUrlBytes(url);
    

    There is an online demo here: http://www.html-to-pdf.net/free-online-pdf-converter.aspx

    0 讨论(0)
提交回复
热议问题