How to create html to pdf in asp.net MVC C#?

How to create html to pdf in asp.net MVC C#?

In this article, you will learn how to create html to pdf in asp.net MVC C# using itextsharp and NReco .net

public static byte[] CreateHTMLtoPDF(string HtmlString)
        {
            var htmlContent = String.Format(HtmlString);
            var htmlToPdf = new NReco.PdfGenerator.HtmlToPdfConverter();
            htmlToPdf.Orientation = NReco.PdfGenerator.PageOrientation.Landscape;
            //var Orientation = new NReco.PdfGenerator.HtmlToPdfConverter().Orientation=NReco.PdfGenerator.PageOrientation.Landscape;
            htmlToPdf.Size = NReco.PdfGenerator.PageSize.A4;
            //htmlToPdf.Zoom = -0.55f;
            var pageMargin = new NReco.PdfGenerator.HtmlToPdfConverter().Margins;
            //htmlToPdf.PageHeight= 210;
            //htmlToPdf.PageWidth = 297;
            pageMargin.Left = 25;
            pageMargin.Right = 25;
            pageMargin.Bottom = 25;
            pageMargin.Top = 25;
            var pdfBytes = htmlToPdf.GeneratePdf(htmlContent);
            byte[] bytes;
            using (MemoryStream input = new MemoryStream(pdfBytes))
            {
                using (MemoryStream output = new MemoryStream())
                {
                    string userpassword = "123";//Change it with User DOB Format dd-MM-yyyy
                    string Ownerpassword = "123";//Change it with whatever owner is wanted
                    PdfReader reader = new PdfReader(input);
                    PdfEncryptor.Encrypt(reader, output, true, userpassword, Ownerpassword, PdfWriter.ALLOW_SCREENREADERS);
                    bytes = output.ToArray();
                    //Response.ContentType = "application/pdf";
                    //Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
                    //Response.Cache.SetCacheability(HttpCacheability.NoCache);
                    //Response.BinaryWrite(bytes);
                    //Response.End();
                }
            }
            return bytes;
        }

2021-10-03