Example #1
0
        //multi PDF
        public void getMultiPDF()
        {
            var HtmlTemplate = "<p>[[NAME]]</p>";
            var Names        = new[] { "John", "James", "Jenny" };

            foreach (var name in Names)
            {
                var HtmlInstance = HtmlTemplate.Replace("[[NAME]]", name);
                var Pdf          = Renderer.RenderHtmlAsPdf(HtmlInstance);
                Pdf.SaveAs(name + ".pdf");
            }
        }
Example #2
0
        public void PdfSharpConvert(int?id)
        {
            var d    = _db.DistrictProfiles.FirstOrDefault(x => x.Id == id);
            var html = PartialView("_table", d).RenderToString();

            IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
            // Render an HTML document or snippet as a string
            Renderer.RenderHtmlAsPdf(html).SaveAs("html-string.pdf");
            // Advanced:
            // Set a "base url" or file path so that images, javascript and CSS can be loaded
            var PDF = Renderer.RenderHtmlAsPdf("<img src='icons/iron.png'>", @"C:\site\assets\");

            PDF.SaveAs("html-with-assets.pdf");
        }
Example #3
0
        public ActionResult Get()
        {
            IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
            var PDF = Renderer.RenderHtmlAsPdf("<h1>Hello World</h1>");

            return(File(PDF.BinaryData, "application/pdf", "download.pdf"));
        }
Example #4
0
        //export invoice to odf
        private void exporteerToolStripMenuItem_Click(object sender, EventArgs e)
        {
            IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
            BTN_Generate.PerformClick();
            Stream         myStream;
            SaveFileDialog saveFileDialog1 = new SaveFileDialog();

            saveFileDialog1.Filter           = "PDF (*.pdf)|*.pdf";
            saveFileDialog1.FilterIndex      = 2;
            saveFileDialog1.RestoreDirectory = true;

            if (saveFileDialog1.ShowDialog() == DialogResult.OK)
            {
                if ((myStream = saveFileDialog1.OpenFile()) != null)
                {
                    var fileStream = myStream as FileStream;

                    Console.WriteLine(fileStream.Name + "path");

                    string path = fileStream.Name;

                    fileStream.Close();
                    myStream.Close();

                    Renderer.RenderHtmlAsPdf(WB_Preview.DocumentText).SaveAs(path);
                }
            }
        }
Example #5
0
        private void faturacao(Aluguer aluguer)
        {
            string textoFatura;

            textoFatura  = "<h1>StarStand</h1>";
            textoFatura += "<hr>";
            textoFatura += "<<h2>Dados do Cliente</h2>";
            textoFatura += "<span>" + aluguer.Utilizadores.Nome + "</span><br>";
            textoFatura += "<span>" + aluguer.Utilizadores.NIF + "</span><br>";
            textoFatura += "<span>" + aluguer.Utilizadores.Morada + "</span><br>";
            textoFatura += "<hr>";
            textoFatura += "<h2>Dados do Carro</h2>";
            textoFatura += "<span><b>Marca :  </b>" + aluguer.CarroAluguer.Marca + "</span><br>";
            textoFatura += "<span><b>Modelo :  </b>" + aluguer.CarroAluguer.Modelo + "</span><br>";
            textoFatura += "<span><b>Matricula :  </b>" + aluguer.CarroAluguer.Matricula + "</span><br>";
            textoFatura += "<span><b>Combustivel :  </b>" + aluguer.CarroAluguer.Combustivel + "</span><br>";
            textoFatura += "<hr>";
            textoFatura += "<h2>Dados do Aluguer</h2>";
            textoFatura += "<span>Iniciada :  " + aluguer.DataInicio.ToLongDateString() + "</span><br>";
            DateTime dataFim = (DateTime)aluguer.DataFim;

            textoFatura += "<span>Finalizada :  " + dataFim.ToLongDateString() + " </span><br>";
            textoFatura += "<span>Valor base :  " + aluguer.CarroAluguer.ValorBase + " €</span><br>";
            textoFatura += "<hr>";
            textoFatura += "<span>Total:" + aluguer.Valor + " €</span><br>";
            IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
            Renderer.RenderHtmlAsPdf(textoFatura).SaveAs(Directory.GetCurrentDirectory() + "\\FaturaAluguer\\" + aluguer.IdAluguer + "_" + aluguer.Utilizadores.Nome + ".pdf");
        }
Example #6
0
        static void Main(string[] args)
        {
            string    path      = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            HtmlToPdf HtmlToPdf = new IronPdf.HtmlToPdf();

            HtmlToPdf.RenderHtmlAsPdf("<p>hello world</p>").SaveAs(@"" + path + "/File.Pdf");
        }
        private static async Task <byte[]> BuildPdf(string html)
        {
            try
            {
                var Renderer = new IronPdf.HtmlToPdf();


                Renderer.PrintOptions.Footer = new HtmlHeaderFooter()
                {
                    Height          = 15,
                    HtmlFragment    = "<center><i>{page} of {total-pages}<i></center>",
                    DrawDividerLine = true
                };


                //Image CDN url
                Renderer.PrintOptions.Header = new HtmlHeaderFooter()
                {
                    HtmlFragment = "<img alt='Link broken' src='" + "https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_92x30dp.png" + "' />"
                };


                IronPdf.PdfDocument PDF = Renderer.RenderHtmlAsPdf(html);
                return(PDF.BinaryData);

                //Save to local
                //var OutputPath = "HtmlToPDF.pdf";
                //PDF.SaveAs(OutputPath);
            }
            catch (Exception ex)
            {
                return(null);
            }
        }
Example #8
0
        // Export PDF
        private void btnExportPDF_Click(object sender, RoutedEventArgs e)
        {
            string    path      = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            HtmlToPdf HtmlToPdf = new IronPdf.HtmlToPdf();

            HtmlToPdf.RenderHtmlAsPdf(this.pdfContent).SaveAs(@"" + path + "/exportedFile.pdf");
        }
        public void GetHtml()
        {
            var homePage = new MaxicoursCovidHomePage(Driver);

            var Renderer = new IronPdf.HtmlToPdf();

            Renderer.PrintOptions.SetCustomPaperSizeInInches(12.5, 20);
            Renderer.PrintOptions.PrintHtmlBackgrounds = true;
            Renderer.PrintOptions.PaperOrientation     = PdfPrintOptions.PdfPaperOrientation.Portrait;
            Renderer.PrintOptions.Title            = "My PDF Document Name";
            Renderer.PrintOptions.EnableJavaScript = true;
            Renderer.PrintOptions.RenderDelay      = 50; //ms
            Renderer.PrintOptions.CssMediaType     = PdfPrintOptions.PdfCssMediaType.Screen;
            Renderer.PrintOptions.DPI                    = 300;
            Renderer.PrintOptions.FitToPaperWidth        = true;
            Renderer.PrintOptions.JpegQuality            = 80;
            Renderer.PrintOptions.GrayScale              = false;
            Renderer.PrintOptions.FitToPaperWidth        = true;
            Renderer.PrintOptions.InputEncoding          = Encoding.UTF8;
            Renderer.PrintOptions.Zoom                   = 100;
            Renderer.PrintOptions.CreatePdfFormsFromHtml = true;
            Renderer.PrintOptions.MarginTop              = 40;
            Renderer.PrintOptions.MarginLeft             = 20;
            Renderer.PrintOptions.MarginRight            = 20;
            Renderer.PrintOptions.MarginBottom           = 40;
            Renderer.PrintOptions.FirstPageNumber        = 1;

            var html = homePage.GetHtml();

            var pdf = Renderer.RenderHtmlAsPdf(html);

            pdf.SaveAs("example.pdf");

            //return html;
        }
Example #10
0
        //print order handler
        public void OnGetReceipt(int inputID)
        {
            orderItems = new List <OrderItem>();
            OrderId    = inputID;
            string html     = string.Format("<h1>Thank you for your order!</h1> <b>Order #:{0}</b><table><thead><tr><th>Service Name</th><th>Quantity</th><th>Service Price</th></tr></thead><tbody>", OrderId);
            string fileName = string.Format("receipt{0}.pdf", OrderId);

            //retrieve all items of the order
            string sql = string.Format("SELECT * FROM services INNER JOIN order_items ON services.service_id = order_items.service_id WHERE order_id={0};", OrderId);

            DataSet ds = DataAccessTier.DB.ExecuteNonScalarQuery(sql);


            foreach (DataRow row in ds.Tables[0].Rows)
            {
                Services  S    = new Services(Convert.ToInt32(row["service_id"]), Convert.ToString(row["service_name"]), Convert.ToString(row["service_description"]), Convert.ToInt32(row["service_price"]));
                OrderItem item = new OrderItem(S, Convert.ToInt32(row["quantity"]));
                totalPrice = totalPrice + (Convert.ToInt32(row["quantity"]) * Convert.ToInt32(row["service_price"]));
                orderItems.Add(item);

                //add to html
                string line = string.Format("<tr><td>{0}</td><td>{1}</td><td>{2}</td></tr>;", Convert.ToString(row["service_name"]), Convert.ToInt32(row["quantity"]), Convert.ToInt32(row["service_price"]));
                html += line;
            }

            string footer = string.Format("</tbody></table><b>Total Price: {0} rub.</b>", totalPrice);

            html += footer;

            //render pdf
            var Renderer = new IronPdf.HtmlToPdf();

            Renderer.RenderHtmlAsPdf(html).SaveAs(fileName);
        }
Example #11
0
        public void Export(string filepath)
        {
            string html   = BuildHTML();
            var    pdfdoc = Renderer.RenderHtmlAsPdf(html);

            pdfdoc.SaveAs(filepath);
        }
Example #12
0
        public void SaveReportAsPDF(List <MetricInfo> infos, string procWeeklyPath, string procAvgWeeklyPath, string procYearlyPath,
                                    string sqlAvgWeeklyPath, string sqlYearlyPath)
        {
            string memoryHTML, processorHTML, dbTableHTML, dbSize, eventsHTML;

            memoryHTML    = string.Empty; //Helper.GetMemoryUsage(infos);
            processorHTML = string.Empty; //Helper.GetProcessorUsage(infos);
            SqlClient clnt = new SqlClient(ConnectionString);

            dbTableHTML = Helper.ConvertToHTMLTable(clnt.SqlDBSizeCheck());
            dbSize      = clnt.SqlTotalSizeCheck();
            eventsHTML  = Helper.EventLogCheck();
            if (string.IsNullOrEmpty(eventsHTML))
            {
                eventsHTML = "No errors related to SQL in last 7 days.";
            }
            else
            {
                eventsHTML = Helper.ConvertToHTMLTable(eventsHTML);
            }
            string fileContent = Helper.createGraphicalHTMLReport(ReportTitle, memoryHTML, processorHTML, dbTableHTML, dbSize, eventsHTML,
                                                                  procWeeklyPath, procAvgWeeklyPath, procYearlyPath, sqlAvgWeeklyPath, sqlYearlyPath);
            var Renderer   = new IronPdf.HtmlToPdf();
            var PDF        = Renderer.RenderHtmlAsPdf(fileContent);
            var OutputPath = string.Format(ReportDirectory + System.IO.Path.DirectorySeparatorChar + "Report_{1}_{0}.pdf"
                                           , DateTime.Today.ToString("yyyyMMdd"), ReportTitle);

            PDF.SaveAs(OutputPath);
        }
        // kaşe veya imzalar için kullanılacak.
        public void WatermarkTst()
        {
            IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
            var pdf = Renderer.RenderHtmlAsPdf("<h1>Ekstre Kapak</h1>");

            pdf.WatermarkAllPages("<h2 style='color:red'>Buraya kapak eklenecek!!</h2>", PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45, "https://www.nuget.org/packages/IronPdf");
            pdf.SaveAs(@"C:\tmp\document\Watermarked.pdf");
        }
Example #14
0
        public async Task <IActionResult> Create([Bind("ID,InvoiceTitle,Price,Tax,Sales,CreationDate")] Invoice invoice)
        {
            System.Diagnostics.Trace.Write("Base Directory is : " + AppDomain.CurrentDomain.BaseDirectory);
            System.Diagnostics.Trace.Write("Current Directory is : " + Environment.CurrentDirectory);

            string startupPath = Environment.CurrentDirectory + "\\temp";
            var    OutputPath  = startupPath + "\\" + invoice.InvoiceTitle + ".pdf";


            if (ModelState.IsValid)
            {
                invoice.ID = Guid.NewGuid();
                _context.Add(invoice);
                await _context.SaveChangesAsync();

                /*PDF Generate Code starts*/
                var Renderer = new IronPdf.HtmlToPdf();

                var html = "<div style=\"width:100%;height:400px;border:1px solid black\">" +
                           "<table><tr><td>Invoice Title</td><td>" + invoice.InvoiceTitle + "</td></tr>" +
                           "<tr><td>Price($)</td><td>" + invoice.Price + "</td></tr>" +
                           "<tr><td>Sales($)</td><td>" + invoice.Sales + "</td></tr>" +
                           "<tr><td>Date</td><td>" + invoice.CreationDate + "</td></tr>" +
                           "</table>" +
                           "</div>";
                var PDF = Renderer.RenderHtmlAsPdf(html);

                Renderer.PrintOptions.MarginTop    = 50; //millimeters
                Renderer.PrintOptions.MarginBottom = 50;
                Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print;
                Renderer.PrintOptions.Header       = new SimpleHeaderFooter()
                {
                    CenterText      = "Invoice: " + invoice.InvoiceTitle,
                    DrawDividerLine = true,
                    FontSize        = 16
                };
                Renderer.PrintOptions.Footer = new SimpleHeaderFooter()
                {
                    LeftText        = DateTime.Now.ToString(),
                    RightText       = "Page {1} of {1}",
                    DrawDividerLine = true,
                    FontSize        = 14
                };


                PDF.SaveAs(OutputPath);
                /*PDF generate code ends*/


                return(RedirectToAction(nameof(Index)));
            }
            return(View(invoice));
        }
        //0=No error
        //1=Bad Path
        //2=Empty flower List
        //3=Unknown IO error
        public int createPDF(List <Flower> flowers, string filename)
        {
            int err = testFilename(filename);

            if (err != 0)
            {
                return(err);
            }

            if (flowers.Count == 0)
            {
                return(2);
            }

            IronPdf.HtmlToPdf renderer = new IronPdf.HtmlToPdf();
            List <string>     htmlList = new List <string>();

            for (int i = 0; i < flowers.Count; i++)
            {
                string flowerHTML = "Latin name: " + flowers[i].getLatinName() + "<br>";
                flowerHTML += "English name: " + flowers[i].getEnglishName() + "<br>";
                flowerHTML += "Botanical family: " + flowers[i].getBotanicalFamily() + "<br>";

                flowerHTML += "<br>Added on: " + flowers[i].getNote().getTimeDate().ToShortDateString() + " " + flowers[i].getNote().getTimeDate().ToShortTimeString() + "<br>";
                flowerHTML += flowers[i].getNote().getNote() + "<br>";

                for (int j = 0; j < flowers[i].pictureList.Count; j++)
                {
                    string pictureHTML = "<br><br><img src='" + flowers[i].pictureList[j].getPath() + "'><br>";

                    pictureHTML += "Photographer: " + flowers[i].pictureList[j].getPhotographer() + "<br>";
                    pictureHTML += "Location: " + flowers[i].pictureList[j].getLocation() + "<br>";
                    pictureHTML += "Picture added on: " + flowers[i].pictureList[j].getTimeDate().ToShortDateString() + " " + flowers[i].pictureList[j].getTimeDate().ToShortTimeString() + "<br>";
                    pictureHTML += flowers[i].pictureList[j].getNote();

                    flowerHTML += pictureHTML;
                }

                htmlList.Add(flowerHTML);
            }

            string html = "";

            for (int i = 0; i < htmlList.Count; i++)
            {
                html += htmlList[i] + "<br><br><br>";
            }

            renderer.RenderHtmlAsPdf(html).SaveAs(filename);

            return(0);
        }
        public string CreatePDFBase64FromHTML()
        {
            string htmlDoc = "<h2>Test</h2>";

            var renderer = new IronPdf.HtmlToPdf();

            var pdf = renderer.RenderHtmlAsPdf(htmlDoc);

            byte[] binaryPDF = pdf.BinaryData;

            string base64String = Convert.ToBase64String(binaryPDF);

            return(base64String);
        }
        private void btnPrintReceipt_Click(object sender, EventArgs e)
        {
            if (string.IsNullOrWhiteSpace(tbx_vietbangchu.Text))
            {
                MessageBox.Show("Bạn phải nhập số tiền bằng chữ", "Lỗi");
                return;
            }
            if (!ckb_rule.Checked)
            {
                MessageBox.Show("Bạn phải check vào điều khoản", "Lỗi");
                return;
            }
            DateTime dateTime     = DateTime.Now;
            string   path         = System.IO.Path.Combine(Environment.CurrentDirectory) + "\\Phieuthuhocphi\\phieuthuhocphi.html";
            string   htmlTemplate = File.ReadAllText(path);
            var      template     = Handlebars.Compile(htmlTemplate);
            var      data         = new
            {
                maphieuthu        = lbl_mathu.Text,
                mahs              = lbl_mahs.Text,
                hovaten           = lbl_ten.Text,
                ngaysinh          = lbl_ngaysinh.Text,
                lop               = lbl_lop.Text,
                nienkhoa          = lbl_nienkhoa.Text,
                khoanthu          = this.khoanthu,
                miengiam          = this.miengiam,
                sotien            = lbl_tongtien.Text,
                sotienvietbangchu = tbx_vietbangchu.Text,
                ngay              = dateTime.Day,
                thang             = dateTime.Month,
                nam               = dateTime.Year
            };
            var result   = template(data);
            var Renderer = new IronPdf.HtmlToPdf();
            var PDF      = Renderer.RenderHtmlAsPdf(result);
            FolderBrowserDialog folderDlg = new FolderBrowserDialog();

            folderDlg.ShowNewFolderButton = true;
            // Show the FolderBrowserDialog.
            DialogResult diaresult = folderDlg.ShowDialog();

            if (diaresult == DialogResult.OK)
            {
                var OutputPath = folderDlg.SelectedPath + "\\Phiếu thu học phí " + lbl_mahs.Text + ".pdf";
                PDF.SaveAs(OutputPath);
                MessageBox.Show("Đã in xong phiếu thu học phí", "Thông báo");
                ckb_rule.Checked = false;
                this.updatePhieuThu();
            }
        }
Example #18
0
        static void Main(string[] args)
        {
            GetUrls();
            if (!Directory.Exists("data"))
            {
                Directory.CreateDirectory("data");

                foreach (var url in GetUrls())
                {
                    var subject = new SubjectDataSheet(url);

                    using (TextWriter WriteFileStream = new StreamWriter("data/" + subject.NameEng + ".xml"))
                    {
                        XmlSerializer SerializerObj = new XmlSerializer(typeof(SubjectDataSheet));

                        SerializerObj.Serialize(WriteFileStream, subject);

                        WriteFileStream.Close();
                        Console.WriteLine("data/" + subject.NameEng + ".xml done");
                    }
                }
            }
            else
            {
                var template = Handlebars.Compile(File.ReadAllText("Views\\sablon.hbs"));

                string[] datafiles = Directory.GetFiles("data");

                Directory.CreateDirectory("out");

                foreach (var filename in datafiles)
                {
                    FileStream ReadFileStream = new FileStream("data\\" + filename, FileMode.Open, FileAccess.Read, FileShare.Read);

                    XmlSerializer SerializerObj = new XmlSerializer(typeof(SubjectDataSheet));

                    // Load the object saved above by using the Deserialize function
                    SubjectDataSheet loadedsubject = (SubjectDataSheet)SerializerObj.Deserialize(ReadFileStream);

                    // Cleanup
                    ReadFileStream.Close();

                    string result = template(loadedsubject);

                    HtmlToPdf printer = new IronPdf.HtmlToPdf();
                    printer.RenderHtmlAsPdf(result).SaveAs("out\\" + filename.Replace(".xml", "") + ".pdf");
                }
            }
            Console.ReadKey();
        }
Example #19
0
        /// <summary>
        /// Takes a raw string from a message, manipulates it and prints out a pdf to the OutPutDir, if none is chosen it defaults to desktop
        /// </summary>
        /// <param name="rawInput">This is the raw string from the message, do not edit it</param>
        public void Create(string rawInput)
        {
            string[] splitString = rawInput.Split(' ');


            // good luck reading this.
            var html = GenerateHtml(splitString[0], splitString[1], splitString[2], splitString[3],
                                    splitString[4], splitString[5], splitString[6], splitString[7],
                                    splitString[8], splitString[9], splitString[10], splitString[11], splitString[12], splitString[13]);

            IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
            Renderer.PrintOptions.CreatePdfFormsFromHtml = true;
            Renderer.RenderHtmlAsPdf(html).SaveAs(OutPutDir);
        }
        public static PdfDocument RenderPDF(string Html)
        {
            var Renderer = new IronPdf.HtmlToPdf();

            Renderer.PrintOptions.InputEncoding    = Encoding.UTF8;
            Renderer.PrintOptions.EnableJavaScript = true;
            Renderer.PrintOptions.RenderDelay      = 500;
            Renderer.PrintOptions.PaperSize        = PdfPrintOptions.PdfPaperSize.Note;
            Renderer.PrintOptions.PaperOrientation = PdfPrintOptions.PdfPaperOrientation.Portrait;
            PdfDocument PDF = Renderer.RenderHtmlAsPdf(Html);

            PDF.WatermarkAllPages(" < h2 style='color:red'>SAMPLE</h2>", PdfDocument.WaterMarkLocation.MiddleCenter, 50, -45, "https://www.nuget.org/packages/IronPdf");
            return(PDF);
        }
        private static IronPdf.PdfDocument RenderPdf(string Html, IronPdf.PdfPrintOptions PrintOptions = null)
        {
            var Renderer = new IronPdf.HtmlToPdf();

            Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Print;
            if (PrintOptions != null)
            {
                Renderer.PrintOptions = PrintOptions;
            }

            PdfDocument Pdf = Renderer.RenderHtmlAsPdf(Html);

            return(Pdf);
        }
        public FileResult Get()
        {
            //tutaj nastepuje wywolanie repozytorium, a anstepnie utworzenie htmla

            var Renderer = new IronPdf.HtmlToPdf();

            Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen;
            var PDF = Renderer.RenderHtmlAsPdf("<h2>" + _cd.Name + "</h2>" + _raport.GenerujRaport());
            //return a  pdf document from a view
            var contentLength = PDF.BinaryData.Length;

            Response.Headers.Add("Content-Length", contentLength.ToString());
            Response.Headers.Add("Content-Disposition", "inline; filename=Document_.pdf");
            return(File(PDF.BinaryData, "application/pdf;"));
        }
Example #23
0
        public ActionResult <string> CreatePdf([FromForm] string HTMLString)
        {
            DateTime currentDate = DateTime.Now;
            //var Renderer = new IronPdf.HtmlToPdf();
            //var PDF = Renderer.RenderHtmlAsPdf(HTMLString);
            var OutputPath = currentDate.Ticks.ToString() + "HtmlToPDF.pdf";
            //PDF.SaveAs(@"C:\Users\gokul.raju\Desktop\Test\" + OutputPath);
            //return (@"C:\Users\gokul.raju\Desktop\Test\" + OutputPath);


            HtmlToPdf HtmlToPdf = new IronPdf.HtmlToPdf();

            HtmlToPdf.RenderHtmlAsPdf(HTMLString).SaveAs(@"C:\Users\gokul.raju\Desktop\Test\" + OutputPath);
            return(@"C:\Users\gokul.raju\Desktop\Test\" + OutputPath);
        }
        public async Task <IActionResult> PrintPdf(JToken html)
        {
            string header = @"<!DOCTYPE html><html><head><meta charset='utf-8'><meta name='viewport' content='width=device-width, initial-scale=1'><title>Izvjestaj</title></head><body>";
            string footer = @"</body></html>";
            string div    = "";
            string datum1 = "";
            string datum2 = "";

            foreach (JProperty x in html)
            {
                if (x.Name == "datum1")
                {
                    datum1 = (string)x.Value;
                }
                else if (x.Name == "datum2")
                {
                    datum2 = (string)x.Value;
                }
                else
                {
                    div += (string)x.Value;
                }
            }
            string completeHTML = header + div + footer;

            IronPdf.HtmlToPdf Renderer = new IronPdf.HtmlToPdf();
            var Pdf    = Renderer.RenderHtmlAsPdf(completeHTML).SaveAs("C:/Users/HP/Desktop/Izvjestaji/izvjestaj (" + datum1 + " - " + datum2 + ").pdf");
            var stream = new FileStream("C:/Users/HP/Desktop/Izvjestaji/izvjestaj (" + datum1 + " - " + datum2 + ").pdf", FileMode.Open);

            return(new FileStreamResult(stream, "application/pdf"));
            //HtmlToPdfConverter convert = new HtmlToPdfConverter();
            //WebKitConverterSettings settings = new WebKitConverterSettings();
            ////HTML string and base URL
            ////Set WebKit path
            //settings.WebKitPath = "C:/Users/HP/Desktop/samir/dnevni_izvjestaj/dnevniIzvjestaj/dnevniIzvjestaj/QtBinariesWindows";
            ////Assign WebKit settings to HTML converter
            //convert.ConverterSettings = settings;
            ////Convert HTML to PDF
            //PdfDocument document = convert.Convert("https://www.facebook.com/");
            ////Save and close the PDF document
            //MemoryStream ms = new MemoryStream();
            //document.Save(ms);
            //document.Close(true);
            //ms.Position = 0;
            //FileStreamResult fileStreamResult = new FileStreamResult(ms, "application/pdf");
            //fileStreamResult.FileDownloadName = "proba.pdf";
            //return fileStreamResult;
        }
Example #25
0
 byte[] IPdfGenerator.GeneratePdfFromHtml(string content)
 {
     try
     {
         if (string.IsNullOrEmpty(content))
         {
             throw new NsiArgumentNullException(DocumentMessages.DocumentContentNotFound);
         }
         HtmlToPdf htmlToPdf = new IronPdf.HtmlToPdf();
         byte[]    data      = htmlToPdf.RenderHtmlAsPdf(content).BinaryData;
         return(data);
     }
     catch (Exception e)
     {
         throw new NsiBaseException(DocumentMessages.PDFGeneratorFailed, e, Common.Enumerations.SeverityEnum.Error);
     }
 }
Example #26
0
        //Gera o Pdf. Parametro Tipo dita o tipo (0 - A4, 1 - Cupom)
        public static void GeraPdf(string Html, string Caminho, int Tipo)
        {
            var Gerador = new IronPdf.HtmlToPdf();

            if (Tipo == 1)
            {
                Gerador.PrintOptions.SetCustomPaperSizeinMilimeters(80, 200);
            }
            Gerador.PrintOptions.MarginLeft   = 5;
            Gerador.PrintOptions.MarginRight  = 5;
            Gerador.PrintOptions.MarginTop    = 5;
            Gerador.PrintOptions.MarginBottom = 5;

            Gerador.RenderHtmlAsPdf(Html).SaveAs(Caminho);
            System.Diagnostics.Process.Start(@"c:\relatorio.pdf");
            Environment.Exit(0);
        }
Example #27
0
        public ConvertToIronPdf(string str, int i)
        {
            string    filename   = @"C:/Users/arnom/Desktop/TestHTML/test";
            Program   p          = new Program();
            string    findBase64 = @"[^a-zA-Z0-9\+\/=]";
            Regex     rgx64      = new Regex(findBase64);
            HtmlToPdf converter  = new HtmlToPdf();

            var html = toHTML(str);
            //File.WriteAllText(filename + ".html", html.ToString());
            //HtmlToPdf.RenderHtmlAsPdf(html).SaveAs(filename + (i + 1) + ".pdf");
            HtmlToPdf   HtmlToPdf = new IronPdf.HtmlToPdf();
            PdfResource PDF       = HtmlToPdf.RenderHtmlAsPdf(html);

            PDF.SaveAs(filename + i + ".pdf");
            //HtmlToPdf.ConvertUrl(filename + (i + 1) + ".html", pdfname + (i + 1) + ".pdf");
        }
Example #28
0
        public string ConvertHTMLToPDF(string content, string path, string fileName)
        {
            HtmlToPdf renderer = new HtmlToPdf();

            CheckDirectory(path);

            var Renderer = new IronPdf.HtmlToPdf();

            var PDF        = Renderer.RenderHtmlAsPdf(content);
            var OutputPath = path + fileName + ".pdf";

            PDF.SaveAs(OutputPath);



            return(OutputPath);
        }
        public FileResult downloadPDF()
        {
            var html            = TempData["html"] as string;
            var pdfPrintOptions = new PdfPrintOptions()
            {
                MarginTop    = 10,
                MarginBottom = 10,
                MarginLeft   = 2,
                MarginRight  = 2,
                Header       = new SimpleHeaderFooter()
                {
                    // CenterText = "{pdf-title}",
                    DrawDividerLine = true,
                    FontSize        = 8
                },
                Footer = new SimpleHeaderFooter()
                {
                    LeftText        = "{date} {time}",
                    RightText       = "Page {page} of {total-pages}",
                    DrawDividerLine = true,
                    FontSize        = 8
                },
                CssMediaType = PdfPrintOptions.PdfCssMediaType.Print
            };
            var Renderer   = new IronPdf.HtmlToPdf(pdfPrintOptions);
            var PDF        = Renderer.RenderHtmlAsPdf(html);
            var OutputPath = Server.MapPath("/File/HtmlToPDF.pdf");//"HtmlToPDF.pdf";E:\Project\GrandShoesLatest latest\POS\PDFDesign\

            //PDF.SaveAs(OutputPath);
            using (var memoryStream = new MemoryStream())
            {
                Response.ContentType = "application/pdf";
                Response.AddHeader("content-disposition", "attachment;  filename=PurchaseOrder.pdf");

                PDF.Stream.WriteTo(Response.OutputStream);
                Response.Flush();
                //Response.End();
            }
            //System.Diagnostics.Process.Start(OutputPath);
            var downloadFile = new FileStreamResult(PDF.Stream, "application/pdf")
            {
                FileDownloadName = "PurchaseOrder.pdf"
            };

            return(downloadFile);
        }
Example #30
0
        private void HTMLString()
        {
            // Render any HTML fragment or document to HTML
            var Renderer = new IronPdf.HtmlToPdf();
            var PDF      = Renderer.RenderHtmlAsPdf("<h1>Hello IronPdf</h1>");

            Renderer.PrintOptions.Footer = new HtmlHeaderFooter()
            {
                HtmlFragment = "<div style='text-align:right'><em style='color:pink'>page {page} of {total-pages}</em></div>"
            };

            var OutputPath = "HtmlToPDF.pdf";

            PDF.SaveAs(OutputPath);
            // This neat trick opens our PDF file so we can see the result in our default PDF viewer
            //   System.Diagnostics.Process.Start(OutputPath);
            Renderer.PrintOptions.CssMediaType = PdfPrintOptions.PdfCssMediaType.Screen;
        }
        public string exportDayProgram(DateTime date, string outName)
        {
            string htmlSource = exportHtmlSource(date);

            string fileName = System.IO.Path.GetTempPath() + outName;
            HtmlToPdf HtmlToPdf = new IronPdf.HtmlToPdf();

            PdfResource pdf = HtmlToPdf.RenderHtmlAsPdf(htmlSource);
            pdf.SaveAs(fileName);

            return MediaManager.Instance.RootPdf(fileName);
        }