Esempio n. 1
0
        public ActionResult ExportarPDF(int OrderID)
        {
            try
            {
                HtmlToPdf converter = new HtmlToPdf();
                ViewBag.ToPDF = "1";
                //string path = HttpContext.Server.MapPath("/Invoice/InvoiceFile?InvoiceID=" + OrderID.ToString());

                SelectPdf.PdfDocument doc = converter.ConvertUrl("http://control.gtwave.com.br/Invoice/InvoiceFile?InvoiceID=" + OrderID);

                ViewBag.ToPDF = "0";
                //doc.Save(System.Web.HttpContext.Current.Response, false, "test.pdf");
                //doc.Close();
                //doc.Save()

                byte[] fileBytes = doc.Save();
                string fileName  = "proposta_" + OrderID.ToString() + ".pdf";
                return(File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName));

                //return Content(String.Format("Arquivo exportado.", OrderID));
            }
            catch (Exception ex)
            {
                return(Content(ex.Message));
            }
        }
Esempio n. 2
0
        public ActionResult CarregarModalEmail(int OrderID)
        {
            try
            {
                context = new DALContext();
                List <UserAdressBook> Contatos = context.AddressBooks.Filter(p => p.Username == User.Identity.Name).ToList();

                HtmlToPdf converter = new HtmlToPdf();
                ViewBag.ToPDF = "1";
                SelectPdf.PdfDocument doc = converter.ConvertUrl("http://control.gtwave.com.br/Invoice/InvoiceFile?InvoiceID=" + OrderID);

                ViewBag.ToPDF = "0";

                byte[] fileBytes = doc.Save();
                string fileName  = "proposta_" + OrderID.ToString() + ".pdf";
                return(File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, fileName));



                //return Content(String.Format("Arquivo exportado.", OrderID));
            }
            catch (Exception ex)
            {
                return(Content(ex.Message));
            }
        }
        public static string A4Html2Pdf(string Html)
        {
            string    Url      = HttpRuntime.AppDomainAppPath;
            string    fileName = "Content/PDF/" + Guid.NewGuid().ToString() + ".pdf";
            string    fullPath = Path.Combine(Url, fileName);
            HtmlToPdf convert  = new HtmlToPdf();

            convert.Options.MarginBottom = 30;
            convert.Options.MarginTop    = 30;
            convert.Options.MarginLeft   = 30;
            convert.Options.MarginRight  = 30;
            convert.Options.PdfPageSize  = PdfPageSize.A4;
            SelectPdf.PdfDocument doc = convert.ConvertHtmlString(Html);

            //FtpWebRequest request = (FtpWebRequest)WebRequest.Create(Url);
            //request.Credentials = new NetworkCredential("sg1-wss1\\itzmoon", "pD74W87h^#");
            //request.Method = WebRequestMethods.Ftp.UploadFile;
            byte[] pdf    = doc.Save();
            Stream stream = new MemoryStream(pdf);

            using (FileStream outputStream = new FileStream(@fullPath, FileMode.OpenOrCreate))
            {
                stream.CopyTo(outputStream);
            }

            return(fullPath);
        }
Esempio n. 4
0
        //********************************************************************************************
        //
        //********************************************************************************************
        public ActionResult PrintPDF(int id)
        {
            // read parameters from the webpage
            string url = Request.Url.Authority + Request.ApplicationPath + "/Quotes/QuoteDetailsPDF/" + id;

            // instantiate a html to pdf converter object
            SelectPdf.HtmlToPdf converter = new SelectPdf.HtmlToPdf();

            // set converter options
            converter.Options.PdfPageSize        = SelectPdf.PdfPageSize.A4;
            converter.Options.PdfPageOrientation = SelectPdf.PdfPageOrientation.Portrait;
            //converter.Options.WebPageWidth = webPageWidth;
            //converter.Options.WebPageHeight = webPageHeight;

            // create a new pdf document converting an url
            SelectPdf.PdfDocument doc = converter.ConvertUrl(url);

            // save pdf document
            byte[] pdf = doc.Save();

            // close pdf document
            doc.Close();

            // return resulted pdf document
            FileResult fileResult = new FileContentResult(pdf, "application/pdf");

            fileResult.FileDownloadName = "Document.pdf";
            return(fileResult);

            //return RedirectToAction("QuoteDetails/" + id);
        }
Esempio n. 5
0
        // POST: contents/Delete/5


        // select pdf library
        public FileStreamResult DownloadZip(string id)
        {
            MemoryStream workStream = new MemoryStream();
            content      content    = db.contents.Find(id);
            // read parameters from the webpage
            string htmlString = content.content_post;


            string      pdf_page_size = "A4";
            PdfPageSize pageSize      = (PdfPageSize)Enum.Parse(typeof(PdfPageSize),
                                                                pdf_page_size, true);

            string             pdf_orientation = "Portrait";
            PdfPageOrientation pdfOrientation  =
                (PdfPageOrientation)Enum.Parse(typeof(PdfPageOrientation),
                                               pdf_orientation, true);

            int webPageWidth = 1024;

            try
            {
                webPageWidth = 1024;
            }
            catch { }

            int webPageHeight = 0;

            try
            {
                webPageHeight = 0;
            }
            catch { }

            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();

            // set converter options
            converter.Options.PdfPageSize        = pageSize;
            converter.Options.PdfPageOrientation = pdfOrientation;
            converter.Options.WebPageWidth       = webPageWidth;
            converter.Options.WebPageHeight      = webPageHeight;

            // create a new pdf document converting an url
            SelectPdf.PdfDocument doc = converter.ConvertHtmlString(htmlString);

            byte[] pdf = doc.Save();
            doc.Close();
            // put pdf into zip
            using (var zip = new ZipFile())
            {
                zip.AddEntry(content.content_id + ".pdf", pdf);
                zip.Save(workStream);
            }
            workStream.Position = 0;
            FileStreamResult fileResult = new FileStreamResult(workStream, System.Net.Mime.MediaTypeNames.Application.Zip);

            fileResult.FileDownloadName = content.content_id + ".zip";
            return(fileResult);
        }
Esempio n. 6
0
        private byte[] HtmlToPdf(string htmlBody, string htmlFooter)
        {
            // get parameters
            string headerUrl = Startup.ServerPath + @"\wwwroot\templates\header.html";
            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();

            // header settings
            converter.Options.DisplayHeader = true;
            converter.Header.Height         = 20;
            PdfHtmlSection headerHtml = new PdfHtmlSection(headerUrl)
            {
                AutoFitHeight = HtmlToPdfPageFitMode.AutoFit
            };

            converter.Header.Add(headerHtml);
            // footer settings
            converter.Options.DisplayFooter = true;
            converter.Footer.Height         = 165;
            PdfHtmlSection footerHtml = new PdfHtmlSection(htmlFooter, null)
            {
                AutoFitHeight = HtmlToPdfPageFitMode.AutoFit,
                AutoFitWidth  = HtmlToPdfPageFitMode.AutoFit,
                WebPageWidth  = 793
            };

            converter.Footer.Add(footerHtml);
            // read parameters from the webpage
            PdfPageSize        pageSize       = PdfPageSize.A4;
            PdfPageOrientation pdfOrientation = PdfPageOrientation.Portrait;
            int webPageWidth  = 793;
            int webPageHeight = 0;

            // set converter options
            converter.Options.PdfPageSize        = pageSize;
            converter.Options.PdfPageOrientation = pdfOrientation;
            converter.Options.WebPageWidth       = webPageWidth;
            converter.Options.WebPageHeight      = webPageHeight;
            converter.Options.MarginLeft         = 0;
            converter.Options.MarginRight        = 0;
            //set document permissions
            converter.Options.SecurityOptions.CanAssembleDocument = false;
            converter.Options.SecurityOptions.CanCopyContent      = true;
            converter.Options.SecurityOptions.CanEditAnnotations  = false;
            converter.Options.SecurityOptions.CanEditContent      = false;
            converter.Options.SecurityOptions.CanPrint            = true;
            converter.Options.PdfDocumentInformation.Title        = "CPD Activity Accreditation";
            converter.Options.PdfDocumentInformation.CreationDate = DateTime.UtcNow;
            converter.Options.PdfDocumentInformation.Subject      = "CPD Activity Accreditation";
            converter.Options.PdfDocumentInformation.Keywords     = "scfhs.org.sa";
            // create a new pdf document converting an url
            SelectPdf.PdfDocument doc = converter.ConvertHtmlString(htmlBody);
            // save pdf document
            byte[] pdf = doc.Save();
            // close pdf document
            doc.Close();
            // return resulted pdf document
            return(pdf);
        }
Esempio n. 7
0
        protected void lnkDownload_Click(object sender, EventArgs e)
        {
            LinkButton lnkDownload = (LinkButton)sender;

            lnkDownload.Enabled = false;
            DataTable dt         = (DataTable)ViewState["TestKey"];
            string    testkey    = dt.Rows[0]["TestKey"].ToString();
            string    currenturl = HttpContext.Current.Request.Url.AbsoluteUri;

            currenturl = currenturl.Split('/')[2];
            string      url           = "http://" + currenturl + "/Teacher/" + "Report.aspx?TestAssignedId=" + lnkDownload.CommandArgument.ToString();
            string      pdf_page_size = "A4";
            PdfPageSize pageSize      = (PdfPageSize)Enum.Parse(typeof(PdfPageSize),
                                                                pdf_page_size, true);

            string pdf_orientation = "Landscape";
            // string pdf_orientation = "Portrait";
            PdfPageOrientation pdfOrientation =
                (PdfPageOrientation)Enum.Parse(typeof(PdfPageOrientation),
                                               pdf_orientation, true);

            int webPageWidth = 1120;

            // int webPageWidth = 1024;
            try
            {
                //   webPageWidth = Convert.ToInt32(1024);
                webPageWidth = Convert.ToInt32(1120);
            }
            catch { }

            int webPageHeight = 0;

            try
            {
                webPageHeight = Convert.ToInt32(0);
            }
            catch { }

            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();

            // set converter options
            converter.Options.PdfPageSize        = pageSize;
            converter.Options.PdfPageOrientation = pdfOrientation;
            converter.Options.WebPageWidth       = webPageWidth;
            converter.Options.WebPageHeight      = webPageHeight;

            // create a new pdf document converting an url
            SelectPdf.PdfDocument doc = converter.ConvertUrl(url);

            // save pdf document
            doc.Save(Response, false, lnkDownload.CommandName + "_" + testkey + ".pdf");

            // close pdf document
            doc.Close();
            lnkDownload.Enabled = true;
        }
Esempio n. 8
0
        /// <summary>
        /// HTML合同模板转PDF
        /// </summary>
        /// <param name="WebRootPath"></param>
        /// <param name="help"></param>
        /// <returns></returns>
        public static byte[] HTMLToPDF(String WebRootPath, ContractHelp help)
        {
            String       TemplatePath = WebRootPath + @"/Template/Template.html";
            StreamReader reader       = new StreamReader(TemplatePath, Encoding.UTF8);
            String       HTMLContent  = reader.ReadToEnd();
            String       PayModel     = String.Empty;

            if (help.PayModel == 10)
            {
                PayModel = "支付宝";
            }
            else if (help.PayModel == 20)
            {
                PayModel = "微信";
            }
            else if (help.PayModel == 30)
            {
                PayModel = "银行转账";
            }
            else if (help.PayModel == 40)
            {
                PayModel = "自定义支付-标签购买";
            }
            HTMLContent = HTMLContent.Replace("{CompanyCategory}", help.CompanyName)
                          .Replace("{PathNo}", help.PathNo)
                          .Replace("{CompanyName}", help.CompanyName)
                          .Replace("{CompanyCode}", help.CommunityCode)
                          .Replace("{CompanyAddress}", help.CompanyAddress)
                          .Replace("{StartTimeYear}", help.StarYear.ToString())
                          .Replace("{StartTimeMonth}", help.StarMonth.ToString())
                          .Replace("{StartTimeDay}", help.StarDay.ToString())
                          .Replace("{EndTimeYear}", help.EndYear.ToString())
                          .Replace("{EndTimeMonth}", help.EndMonth.ToString())
                          .Replace("{EndTimeDay}", help.EndDay.ToString())
                          .Replace("{Years}", help.ContractYear.ToString())
                          .Replace("{CompanyVersion}", help.VersionName)
                          .Replace("{Moneys}", Money(help).ToString())
                          .Replace("{MeneyUp}", XExten.XPlus.XPlusEx.XConvertCHN(Money(help)))
                          .Replace("{ServerItems}", help.VersionDes)
                          .Replace("{PayModel}", PayModel);
            HtmlToPdf converter = new HtmlToPdf();

            converter.Options.PdfPageSize        = PdfPageSize.A4;
            converter.Options.PdfStandard        = PdfStandard.Full;
            converter.Options.PdfPageOrientation = PdfPageOrientation.Portrait;
            converter.Options.WebPageWidth       = 1024;
            converter.Options.WebPageHeight      = 0;
            converter.Options.EmbedFonts         = true;
            converter.Options.MarginLeft         = 60;
            converter.Options.MarginRight        = 60;
            converter.Options.MarginTop          = 60;
            converter.Options.MarginBottom       = 60;

            SelectPdf.PdfDocument doc = converter.ConvertHtmlString(HTMLContent);
            byte[] bytes = doc.Save();
            doc.Close();
            return(bytes);
        }
Esempio n. 9
0
        public void pdf()
        {
            string htmlString = "";
            var    file       = (System.Web.HttpContext.Current.Server.MapPath("~/") + "practice-hours.html");
            var    html       = "<TR VALIGN=TOP><TD WIDTH=75 STYLE='border-top: 3.00pt solid #6773b6; border-bottom: 3.00pt solid #6773b6; border-left: 3.00pt solid #6773b6; border-right: none; padding-top: 0in; padding-bottom: 0in; padding-left: 0.08in; padding-right: 0in'>"
                                + "<P CLASS='western' STYLE='widows: 0; orphans: 0;padding-top:12px;'><FONT COLOR='#5162a5'><FONT FACE='Arial, sans-serif'><FONT SIZE=2><SPAN LANG='en-GB'><B>Dates:</B></SPAN></FONT></FONT></FONT></P></TD>" +
                                "<TD WIDTH=115 STYLE='border-top: 3.00pt solid #6773b6; border-bottom: 3.00pt solid #6773b6; border-left: 3.00pt solid #6773b6; border-right: none; padding-top: 0in; padding-bottom: 0in; padding-left: 0.08in; padding-right: 0in'>" +
                                "<P CLASS='western' STYLE='widows: 0; orphans: 0;padding-top:12px;'><FONT COLOR='#5162a5'><FONT FACE='Arial, sans-serif'><FONT SIZE=2><SPAN LANG='en-GB'><B>Name and address of <BR> organisation:</B></SPAN></FONT></FONT></FONT></P></TD>" +
                                "<TD WIDTH=115 STYLE='border-top: 3.00pt solid #6773b6; border-bottom: 3.00pt solid #6773b6; border-left: 3.00pt solid #6773b6; border-right: none; padding-top: 0in; padding-bottom: 0in; padding-left: 0.08in; padding-right: 0in'>" +
                                "<P CLASS='western' STYLE='widows: 0; orphans: 0;padding-top:12px;'><FONT COLOR='#5162a5'><FONT FACE='Arial, sans-serif'><FONT SIZE=2><SPAN LANG='en-GB'><B>Name and address of <BR> organisation:</B></SPAN></FONT></FONT></FONT></P></TD>" +
                                "<TD WIDTH=115 STYLE='border-top: 3.00pt solid #6773b6; border-bottom: 3.00pt solid #6773b6; border-left: 3.00pt solid #6773b6; border-right: none; padding-top: 0in; padding-bottom: 0in; padding-left: 0.08in; padding-right: 0in'>" +
                                "<P CLASS='western' STYLE='widows: 0; orphans: 0;padding-top:12px;'><FONT COLOR='#5162a5'><FONT FACE='Arial, sans-serif'><FONT SIZE=2><SPAN LANG='en-GB'><B>Name and address of <BR> organisation:</B></SPAN></FONT></FONT></FONT></P></TD>" +
                                "<TD WIDTH=115 STYLE='border-top: 3.00pt solid #6773b6; border-bottom: 3.00pt solid #6773b6; border-left: 3.00pt solid #6773b6; border-right: none; padding-top: 0in; padding-bottom: 0in; padding-left: 0.08in; padding-right: 0in'>" +
                                "<P CLASS='western' STYLE='widows: 0; orphans: 0;padding-top:12px;'><FONT COLOR='#5162a5'><FONT FACE='Arial, sans-serif'><FONT SIZE=2><SPAN LANG='en-GB'><B>Name and address of <BR> organisation:</B></SPAN></FONT></FONT></FONT></P></TD>" +
                                "<TD WIDTH=115 STYLE='border-top: 3.00pt solid #6773b6; border-bottom: 3.00pt solid #6773b6; border-left: 3.00pt solid #6773b6; border-right: none; padding-top: 0in; padding-bottom: 0in; padding-left: 0.08in; padding-right: 0in'>" +
                                "<P CLASS='western' STYLE='widows: 0; orphans: 0;padding-top:12px;'><FONT COLOR='#5162a5'><FONT FACE='Arial, sans-serif'><FONT SIZE=2><SPAN LANG='en-GB'><B>Name and address of <BR> organisation:</B></SPAN></FONT></FONT></FONT></P></TD>" +
                                "<TD WIDTH=266 STYLE=border: 3.00pt solid #6773b6; padding-top: 0.08in; padding-bottom: 0.08in; padding-left: 0.08in; padding-right: 0.39in'><P CLASS='western' STYLE='margin-bottom: 0in; widows: 0; orphans: 0;padding-top:6px;'>" +
                                "<FONT COLOR=\"#5162a5\"><FONT FACE=\"Arial, sans-serif\"><FONT SIZE=2><SPAN LANG=\"en-GB\"><B>Brief description of your work:</B></SPAN></FONT></FONT></FONT></P><P LANG=\"en-GB\" STYLE=\"margin-right: -0.34in; widows: 0; orphans: 0\">" +
                                "<BR></P></TD></TR>";

            using (StreamReader sr1 = new StreamReader(file))
            {
                htmlString = sr1.ReadToEnd();
            }
            htmlString = htmlString.Replace("@practicehours@", html);
            string baseUrl = System.Web.HttpContext.Current.Server.MapPath("~/");

            string      pdf_page_size = "A4";
            PdfPageSize pageSize      = (PdfPageSize)Enum.Parse(typeof(PdfPageSize), pdf_page_size, true);

            string             pdf_orientation = "Portrait";
            PdfPageOrientation pdfOrientation  = (PdfPageOrientation)Enum.Parse(typeof(PdfPageOrientation), pdf_orientation, true);

            int webPageWidth = 1024;


            int webPageHeight = 0;

            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();

            // set converter options
            converter.Options.PdfPageSize        = pageSize;
            converter.Options.PdfPageOrientation = pdfOrientation;
            converter.Options.WebPageWidth       = webPageWidth;
            converter.Options.WebPageHeight      = webPageHeight;

            // create a new pdf document converting an url
            SelectPdf.PdfDocument doc = converter.ConvertHtmlString(htmlString, baseUrl);

            // save pdf document
            //doc.Save("Vehicle.pdf");
            doc.Save(baseUrl + "Sample.pdf");
            // close pdf document
            doc.Close();
        }
    private void sendEmail(SurveyTaken surveyresponse, Survey survey)
    {
        //Build Email Body and Subject
        bool yes_no_hit = false, comment_entered = false, detractor = false;

        string recipient = sqlconnector.getUserEmail(survey.getUserID());

        MailMessage mailMessage = new MailMessage("*****@*****.**", recipient);

        mailMessage.Subject = "New Survey Response | " + survey.getTittle();
        StringBuilder emailBody = new StringBuilder();

        string emailBodyreasons = "";

        if (detractor)
        {
            mailMessage.Subject += "DETRACTOR | ";
            emailBodyreasons    += "Detractor | ";
        }
        if (yes_no_hit)
        {
            mailMessage.Subject += "YES/NO TARGET HIT | ";
            emailBodyreasons    += "Yes/No Target Hit | ";
        }
        if (comment_entered)
        {
            mailMessage.Subject += "COMMENT ENTERED | ";
            emailBodyreasons    += "Comment Entered";
        }

        //mailMessage.Subject += "Survey response alert for " + survey.getTittle() + ".";
        mailMessage.Body += "<p>See attached for survey response.</p>";
        mailMessage.Body += "<p>You are reieving this because you have notifications enabled. You can disable them by editing the survey.</p>";

        // Build PDF
        SelectPdf.PdfDocument doc = buildPDF(surveyresponse, survey);

        using (MemoryStream memoryStream = new MemoryStream())
        {
            doc.Save(memoryStream);
            byte[] bytes = memoryStream.ToArray();
            memoryStream.Close();
            mailMessage.Attachments.Add(new Attachment(new MemoryStream(bytes), survey.getTittle() + "_Response_" + surveyresponse.getSurveyTakenID() + ".pdf"));
        }

        SmtpClient smtpClient = new SmtpClient("smtp.gmail.com", 587);

        smtpClient.Credentials = new System.Net.NetworkCredential()
        {
            UserName = "******",
            Password = "******"
        };
        mailMessage.IsBodyHtml = true;
        smtpClient.EnableSsl   = true;
        smtpClient.Send(mailMessage);
    }
Esempio n. 11
0
        public static byte[] generatePDF(string uuid, string pathStyle, ApplicationDbContext _context, IWebHostEnvironment _environment)
        {
            List <string> rutasDelete = new List <string>();
            CFDIDatos     datos       = new CFDIDatos();

            datos = _context.CFDIs.FirstOrDefault(d => d.CfdUUID == uuid);

            var XSLpath = Path.Combine(_environment.WebRootPath, pathStyle);
            //var XSLpath = Path.Combine(_environment.WebRootPath, "images", "CFDI33_Pagos_Nomina.xsl");
            var XMLpath = Path.Combine(_environment.WebRootPath, "temp", uuid + ".xml");//eliminar

            rutasDelete.Add(XMLpath);

            using (FileStream fs = System.IO.File.Create(XMLpath))
            {
                fs.Write(datos.CfdXml, 0, datos.CfdXml.Length);
            }

            var    pathPDF            = Path.Combine(_environment.WebRootPath, "temp", "CFDI-" + uuid + ".pdf"); //eliminar
            string resultname         = "CFDI-" + uuid + ".html";
            var    result             = Path.Combine(_environment.WebRootPath, "temp", resultname);              //eliminar
            XslCompiledTransform xslt = new XslCompiledTransform();

            xslt.Load(XSLpath);
            xslt.Transform(XMLpath, result);

            rutasDelete.Add(result);

            byte[] buffer = null;
            using (FileStream fs = new FileStream(result, FileMode.Open, FileAccess.Read))
            {
                buffer = new byte[fs.Length];
                fs.Read(buffer, 0, (int)fs.Length);
            }
            string contenido  = System.IO.File.ReadAllText(result);
            var    textReader = new StringReader(contenido);

            // instantiate the html to pdf converter
            HtmlToPdf converter = new HtmlToPdf();

            // convert the url to pdf
            SelectPdf.PdfDocument doc = converter.ConvertHtmlString(contenido);
            byte[] pdf = null;
            // save pdf document
            doc.Save(pathPDF);
            // close pdf document
            doc.Close();

            using (FileStream documentStream = new FileStream(pathPDF, FileMode.Open, FileAccess.Read))
            {
                pdf = new byte[documentStream.Length];
                documentStream.Read(pdf, 0, (int)documentStream.Length);
            }
            return(pdf);
        }
Esempio n. 12
0
        public MemoryStream Message2Pdf(MimeMessage message)
        {
            MemoryStream msMail = new MemoryStream();
            string       html   = message.GetTextBody(MimeKit.Text.TextFormat.Html);
            string       txt    = message.GetTextBody(MimeKit.Text.TextFormat.Text);

            HtmlToPdf converter = new HtmlToPdf();

            SelectPdf.PdfDocument pdfdok = null;
            if (html != null)
            {
                pdfdok = converter.ConvertHtmlString(html);
            }
            else
            {
                if (string.IsNullOrEmpty(txt))
                {
                    txt = "Tom email";
                }
                pdfdok = converter.ConvertHtmlString(txt);
            }
            pdfdok.Save(msMail);
            msMail.Position = 0;

            XPdfForm form = XPdfForm.FromStream(msMail);

            PdfSharp.Pdf.PdfDocument outputDocument = new PdfSharp.Pdf.PdfDocument();
            XGraphics gfx;

            int count = form.PageCount;

            for (int idx = 0; idx < count; idx++)
            {
                PdfSharp.Pdf.PdfPage page = outputDocument.AddPage();
                if (form.PageCount > idx)
                {
                    // Get a graphics object for page
                    gfx = XGraphics.FromPdfPage(page);
                    if (idx == 0)
                    {
                        DrawPageHeading(page, gfx, message);
                        // Draw the page like an image
                        gfx.DrawImage(form, new XRect(form.PointWidth * 0.02, form.PointHeight * 0.10, form.PointWidth * 0.90, form.PointHeight * 0.90));
                    }
                    else
                    {
                        gfx.DrawImage(form, new XRect(form.PointWidth, form.PointHeight, form.PointWidth, form.PointHeight));
                    }
                }
            }
            msMail = new MemoryStream();
            outputDocument.Save(msMail, false);
            return(msMail);
        }
        //protected void btnOK_Click(object sender, EventArgs e) {
        //    Process p = new Process();
        //    p.StartInfo = new ProcessStartInfo()
        //    {
        //        CreateNoWindow = true,
        //        Verb = "print",
        //        FileName = @"C:\Users\pee.ti3\desktop\pedf122.pdf" //put the correct path here
        //    };
        //    p.Start();
        //}

        //public void pd_PrintPage(object sender, PrintPageEventArgs e)
        //{
        //    string labelPath = ((PrintDocument)sender).DocumentName;
        //    e.Graphics.DrawImage(new Bitmap(labelPath), 0, 0);
        //}


        public static void htmlAPDF()
        {
            // -------- Convertir HTML de solicitudes a PDF --------
            HtmlToPdf converter = new HtmlToPdf();

            // convert the url to pdf
            SelectPdf.PdfDocument doc = converter.ConvertUrl("http://cablesmtymxdev2/scripts/cgiip.exe/WService=xcmsafin/Flujo_FM_qad2011/comp_otras.w?DomainCode=MFGCMSA&ref=155506&num_sistema=11&h_sesion=1098541&global_user=0000136&entidad=2000");
            // save pdf document
            doc.Save(@"C:\Users\pee.ti3\Desktop\testOutput.pdf");
            // close pdf document
            doc.Close();
        }
Esempio n. 14
0
        public static byte[] ConvertHtml2Pdf(string content)
        {
            HtmlToPdf converter = new HtmlToPdf();

            converter.Options.PdfPageSize        = PdfPageSize.A4;
            converter.Options.PdfPageOrientation = PdfPageOrientation.Portrait;
            SelectPdf.PdfDocument doc = converter.ConvertHtmlString(content);
            var data = doc.Save();

            doc.Close();
            return(data);
        }
Esempio n. 15
0
        private byte[] GeneratePdfReport(string invoiceid)
        {
            byte[]    result       = null;
            int       Invoiceid    = Convert.ToInt32(invoiceid);
            HtmlToPdf objPdfSelect = new HtmlToPdf();
            var       htmlurl      = "";

            try
            {
                htmlurl = "http://localhost:44324/PDF/Report?Invoiceid=" + Invoiceid;
                objPdfSelect.Options.MarginTop    = 5;
                objPdfSelect.Options.MarginBottom = 5;
                objPdfSelect.Options.MarginLeft   = 10;
                objPdfSelect.Options.MarginRight  = 10;
                objPdfSelect.Options.ViewerPreferences.CenterWindow    = true;
                objPdfSelect.Options.ViewerPreferences.DisplayDocTitle = true;
                objPdfSelect.Options.ViewerPreferences.FitWindow       = true;
                objPdfSelect.Options.ViewerPreferences.HideMenuBar     = true;
                objPdfSelect.Options.ViewerPreferences.HideToolbar     = true;
                objPdfSelect.Options.ViewerPreferences.HideWindowUI    = true;
                objPdfSelect.Options.ViewerPreferences.PageMode        = PdfViewerPageMode.UseNone;
                objPdfSelect.Options.DisplayHeader     = true;
                objPdfSelect.Options.DisplayFooter     = true;
                objPdfSelect.Header.DisplayOnFirstPage = true;
                PDFDLController obj    = new PDFDLController();
                reportmodel     output = new reportmodel();
                output             = obj.Reportpdf(Invoiceid);
                ViewData["Report"] = output;
                ViewData.Model     = ViewData["Report"];
                StringWriter     stringWriter = new StringWriter();
                ViewEngineResult viewResult   = ViewEngines.Engines.FindView(ControllerContext, "Report", null);
                ViewContext      viewContext  = new ViewContext(
                    ControllerContext,
                    viewResult.View,
                    new ViewDataDictionary(ViewData.Model),
                    new TempDataDictionary(),
                    stringWriter
                    );
                viewResult.View.Render(viewContext, stringWriter);
                string htmlToConvert          = stringWriter.ToString();
                SelectPdf.PdfDocument pdffile = objPdfSelect.ConvertHtmlString(htmlToConvert);
                result = pdffile.Save();
                pdffile.Close();
            }
            catch (Exception ex)
            {
                throw ex;
            }

            return(result);
        }
Esempio n. 16
0
        public IActionResult GeneratePdf(string html)
        {
            html = html.Replace("StrTag", "<").Replace("EndTag", ">");
            HtmlToPdf oHtmlToPdf = new HtmlToPdf();

            SelectPdf.PdfDocument oPdfDocument = oHtmlToPdf.ConvertHtmlString(html);
            byte[] pdf = oPdfDocument.Save();
            oPdfDocument.Close();
            return(File(
                       pdf,
                       "application/pdf",
                       "ProductList.pdf"
                       ));
        }
Esempio n. 17
0
    protected void Button1_Click1(object sender, EventArgs e)
    {
        string  c   = "<tr><th><b>SERIAL NO.</b></th><th><b>MAKER DESCRIPTION</b></th><th><b>MODEL DESCRIPTION</b></th><th><b>WEIGHT</b></th><th><b>REGISTRATION NO</b></th></tr>";
        DataSet use = datas();

        for (int i = 0; i < use.Tables[0].Rows.Count; i++)
        {
            c = c + "<tr><td style='text-align:center; padding:1px 10px 1px 10px'>" + (i + 1).ToString() + "</td><td style=\"padding:1px 10px 1px 10px\">" + use.Tables[0].Rows[i][0].ToString() + "</td><td style=\"padding:1px 10px 1px 10px\">" + use.Tables[0].Rows[i][1].ToString() + "</td><td style='text-align:right; padding:1px 10px 1px 10px'>" + use.Tables[0].Rows[i][2].ToString() + "</td><td style=\"padding:1px 10px 1px 10px\">" + use.Tables[0].Rows[i][3].ToString() + "</td></tr>";
        }
        string    s         = "<html><body><table border=1 width=100% >" + c + "</table></body></html>";
        HtmlToPdf converter = new HtmlToPdf();

        SelectPdf.PdfDocument doc = converter.ConvertHtmlString(s);
        doc.Save(Server.MapPath("~/pdf/model.pdf"));
        Session["viewmodel"] = 1;
        Response.Redirect("viewmodel.aspx");
    }
Esempio n. 18
0
        public FileResult GenerateAdminReportPdf(string date)
        {
            var tempHtmlTemplate = AppDomain.CurrentDomain.BaseDirectory + @"Content\AdminReport.html";
            var model            = new List <ReportVM>();

            string[] startDateSplit = date.Split(',');
            DateTime?startDate      = null;
            DateTime?endDate        = null;

            if (startDateSplit.Count() >= 2)
            {
                startDate = Convert.ToDateTime(startDateSplit[0]);
                endDate   = (Convert.ToDateTime(startDateSplit[1])).AddHours(23).AddMinutes(59);
                //endDate = endDate.Value.AddHours(23).AddMinutes(59);
            }
            model = _adminService.GetReportData(startDate, endDate);

            string        str = RenderPartialToString(this, "AdminReport", model, ViewData, TempData);
            StringBuilder sb  = new StringBuilder();

            foreach (var item in model)
            {
                string htmlFormat =
                    $"<tr><td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{item.Request}</td>"
                    + $"<td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{item.EligibleProperties}</td>"
                    + $"<td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{item.InEligibleProperties}</td>"
                    + $"<td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{item.Unknown}</td>";
                sb.Append(htmlFormat);
            }
            str = str.Replace("#######", sb.ToString());
            System.IO.File.WriteAllText(tempHtmlTemplate, str);
            SelectPdf.HtmlToPdf pdfFile = new SelectPdf.HtmlToPdf();
            pdfFile.Options.MarginRight = 5;
            pdfFile.Options.MarginRight = 5;
            SelectPdf.PdfDocument document = pdfFile.ConvertUrl(tempHtmlTemplate);
            //Guid rand = Guid.NewGuid();
            //string pdf = Server.MapPath("/Content/test"+ rand+".pdf");
            byte[] pd = document.Save();
            document.Close();
            FileResult fileResult = new FileContentResult(pd, "application/pdf");

            fileResult.FileDownloadName = "Report" + DateTime.Now + ".pdf";
            return(fileResult);
        }
Esempio n. 19
0
        public Byte[] ConvertHtmlCodeToPdf(string html, string footerHml)
        {
            int webPageWidth  = 1050;
            int webPageHeight = 0;



            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();

            // set converter options
            converter.Options.PdfPageSize   = PdfPageSize.A4;
            converter.Options.MarginLeft    = 0;
            converter.Options.MarginRight   = 0;
            converter.Options.MarginTop     = 0;
            converter.Options.MarginBottom  = 0;
            converter.Options.DisplayFooter = true;
            // BuildMyString.com generated code. Please enjoy your string responsibly.

            if (!string.IsNullOrEmpty(footerHml))
            {
                PdfHtmlSection footerHtml = new PdfHtmlSection(footerHml, "");
                converter.Footer.Add(footerHtml);
                converter.Footer.Height  = 50;
                footerHtml.AutoFitHeight = HtmlToPdfPageFitMode.AutoFit;
            }


            converter.Options.PdfPageOrientation = PdfPageOrientation.Portrait;
            converter.Options.WebPageWidth       = webPageWidth;
            converter.Options.WebPageHeight      = webPageHeight;

            // create a new pdf document converting an url
            SelectPdf.PdfDocument doc = converter.ConvertHtmlString(html, _baseUrl);

            // save pdf document
            byte[] pdf = doc.Save();

            // close pdf document
            doc.Close();

            return(pdf);
        }
Esempio n. 20
0
        public static void PrintFromHTML(CMS_OrderModels modelOrder, string path)
        {
            var body = CommonHelper.CreateBodyMail(modelOrder);

            HtmlToPdf converter = new HtmlToPdf();

            converter.Options.PdfPageSize   = PdfPageSize.A5;
            converter.Options.WebPageWidth  = 650;
            converter.Options.WebPageHeight = 0;

            // convert the url to pdf
            SelectPdf.PdfDocument doc = converter.ConvertHtmlString(body);

            // save pdf document
            doc.Save(path);

            // close pdf document
            doc.Close();
        }
Esempio n. 21
0
        public async Task <FileStreamResult> RenderViewAsPdf(string viewName, object model, string fileName)
        {
            var htmlString = await RenderViewAsHtml(viewName, model);

            MemoryStream inMemoryStream = new MemoryStream();

            SelectPdf.HtmlToPdf   converter = new SelectPdf.HtmlToPdf();
            SelectPdf.PdfDocument doc       = converter.ConvertHtmlString(htmlString);
            doc.Save(inMemoryStream);
            doc.Close();
            inMemoryStream.Seek(0, SeekOrigin.Begin);
            var retStream = new FileStreamResult(inMemoryStream, new MediaTypeHeaderValue("application/pdf"));

            if (!string.IsNullOrEmpty(fileName))
            {
                retStream.FileDownloadName = fileName;
            }
            return(retStream);
        }
Esempio n. 22
0
        public static byte[] GetSelectPdf(string htmlString, PdfPageSize pdfPageSize, string Titulo = "", string Autor = "", string Asunto = "", string PalabraClave = "")
        {
            byte[] PDFBytes = null;
            try
            {
                SelectPdf.HtmlToPdf htmlToPdf = new SelectPdf.HtmlToPdf();

                htmlToPdf.Options.PdfPageSize        = pdfPageSize;
                htmlToPdf.Options.PdfPageOrientation = PdfPageOrientation.Portrait;
                htmlToPdf.Options.AutoFitWidth       = HtmlToPdfPageFitMode.ShrinkOnly;
                htmlToPdf.Options.WebPageWidth       = 1000;
                htmlToPdf.Options.WebPageHeight      = 0;
                htmlToPdf.Options.MarginLeft         = 0;
                htmlToPdf.Options.MarginRight        = 0;
                htmlToPdf.Options.MarginTop          = 0;
                htmlToPdf.Options.MarginBottom       = 0;

                htmlToPdf.Options.PdfDocumentInformation.Title        = Titulo;
                htmlToPdf.Options.PdfDocumentInformation.Author       = Autor;
                htmlToPdf.Options.PdfDocumentInformation.CreationDate = DateTime.Now;
                htmlToPdf.Options.PdfDocumentInformation.Subject      = Asunto;
                htmlToPdf.Options.PdfDocumentInformation.Keywords     = PalabraClave;
                //htmlToPdf.Options.JavaScriptEnabled = true;
                htmlToPdf.Options.RenderingEngine = RenderingEngine.WebKitRestricted;
                //htmlToPdf.Options.RenderPageOnTimeout = true;
                //htmlToPdf.Options.MinPageLoadTime = 2;
                //htmlToPdf.Options.CssMediaType = HtmlToPdfCssMediaType.Screen;
                SelectPdf.PdfDocument pdf = htmlToPdf.ConvertHtmlString(htmlString);

                MemoryStream ms = new MemoryStream();
                pdf.Save(ms);
                pdf.Close();

                PDFBytes = ms.ToArray();
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return(PDFBytes);
        }
Esempio n. 23
0
        public ActionResult EnviarEmailAttached(SendMailViewModel model, int OrderID)
        {
            try
            {
                model.Order.Id = OrderID;

                string saudacao = "Bom dia.";

                if (DateTime.Now.Hour >= 12)
                {
                    saudacao = "Boa Tarde.";
                }

                HtmlToPdf converter = new HtmlToPdf();
                ViewBag.ToPDF = "1";
                SelectPdf.PdfDocument doc = converter.ConvertUrl("http://control.gtwave.com.br/Invoice/InvoiceFile?InvoiceID=" + model.Order.Id.ToString());

                //if (model.Order.Id > 0)
                //{
                //    doc = converter.ConvertUrl("http://control.gtwave.com.br/Invoice/InvoiceFile?InvoiceID=" + model.Order.Id);
                //}

                ViewBag.ToPDF = "0";

                byte[] fileBytes = doc.Save();
                string fileName  = "proposta_" + model.Order.Id.ToString() + ".pdf";

                FileStream fs = new FileStream(AppDomain.CurrentDomain.BaseDirectory + "anexos\\" + fileName, FileMode.OpenOrCreate);
                fs.Write(fileBytes, 0, fileBytes.Length);
                fs.Close();

                Utilidades.EnvioEmail.EmailHelper.SendMailTemplate(model.Order.ProposalMailList, model.Assunto,
                                                                   saudacao + "<br /><br /> Segue a proposta solicitada. <br /><br />Atenciosamente,", AppDomain.CurrentDomain.BaseDirectory + "anexos\\" + fileName, AppDomain.CurrentDomain.BaseDirectory);
            }
            catch (Exception ex)
            {
                return(Content("Não foi possível enviar o email. " + ex.Message));
            }
            return(Content("Email Enviado com sucesso."));
        }
Esempio n. 24
0
        public FileResult GenerateProjectReportPdf()
        {
            var tempHtmlTemplate = AppDomain.CurrentDomain.BaseDirectory + @"Content\CoverSheet.html";
            var model            = new List <CoverSheetVM>();

            model = _requestService.GetCoverSheetUsers();

            string        str = RenderPartialToString(this, "ProjectReport", model, ViewData, TempData);
            StringBuilder sb  = new StringBuilder();

            foreach (var item in model)
            {
                string htmlFormat = string.Format(
                    "<tr><td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{0}</td>"
                    + "<td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{1}</td>"
                    + "<td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{2}</td>"
                    + "<td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{3}</td>"
                    + "<td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{4}</td>"
                    + "<td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{5}</td>"
                    + "<td style='padding: 3px 15px; border: 1px solid #ddd; font-family:arial;'>{6}</td>"
                    , item.ProjectLogNumber, item.Date, item.ProjectName, item.ApplicantContact.Name, item.ApplicantContact.CountyName, item.LeadLegacy, item.ProjectDescription
                    );
                sb.Append(htmlFormat);
            }
            str = str.Replace("#######", sb.ToString());
            System.IO.File.WriteAllText(tempHtmlTemplate, str);
            SelectPdf.HtmlToPdf pdfFile = new SelectPdf.HtmlToPdf();
            pdfFile.Options.MarginRight = 5;
            pdfFile.Options.MarginRight = 5;
            SelectPdf.PdfDocument document = pdfFile.ConvertUrl(tempHtmlTemplate);
            //Guid rand = Guid.NewGuid();
            //string pdf = Server.MapPath("/Content/test"+ rand+".pdf");
            byte[] pd = document.Save();
            document.Close();
            FileResult fileResult = new FileContentResult(pd, "application/pdf");

            fileResult.FileDownloadName = "Document.pdf";
            return(fileResult);
        }
        public async Task <ActionResult> DownloadPdf([FromBody] PdfModel pdf)
        {
            List <RecipeViewModel> recipes = new List <RecipeViewModel>();
            var result = await _recipeSevice.GetRecipes();

            foreach (string item in pdf.Recipes)
            {
                var local = result.First(r => r.Id == item);
                recipes.Add(local);
            }
            var html = _pdfGeneratorService.ToHtmlString(recipes, pdf.Title);

            MemoryStream memoryStream = new MemoryStream();
            TextWriter   tw           = new StreamWriter(memoryStream);

            HtmlToPdf converter = new HtmlToPdf();

            //tw.WriteLine(html);
            SelectPdf.PdfDocument doc = converter.ConvertHtmlString(html);

            doc.Save(memoryStream);
            doc.Close();
            memoryStream.Position = 0;

            FileStreamResult fileStreamResult = new FileStreamResult(memoryStream, "application/pdf");

            return(fileStreamResult);


            //MemoryStream memory = new MemoryStream();
            ////using (FileStream stream = new FileStream(@"C:\Users\baptiste\Downloads", FileMode.Open))
            ////{
            ////    await stream.CopyToAsync(memory);
            ////}

            //memory.Position = 0;

            //return File(memory, "application/force-download", "test.pdf");
        }
Esempio n. 26
0
        public FileInfo GenerateInvoicePdf(InvoiceData data)
        {
            string html = GetInvoiceHtml(data);

            HtmlToPdf converter = new HtmlToPdf();

            converter.Options.PdfPageSize        = PdfPageSize.A4;
            converter.Options.PdfPageOrientation = PdfPageOrientation.Portrait;
            converter.Options.WebPageWidth       = converter.Options.WebPageHeight = 100;

            if (!Directory.Exists(_options.PdfDirectory))
            {
                Directory.CreateDirectory(_options.PdfDirectory);
            }
            SelectPdf.PdfDocument doc = converter.ConvertHtmlString(html, _options.HtmlTemplatePath);
            string pdfPath            = Path.Combine(_options.PdfDirectory, GetPdfName());

            doc.Save(pdfPath);
            doc.Close();

            return(new FileInfo(pdfPath));
        }
Esempio n. 27
0
        //public bool CreateDoc(long correspondenceId, string correspondenceTypeName, string body)
        //{
        //    Document document = new Document();
        //    return true;
        //}

        public bool CreatePdf(long correspondenceId, string correspondenceTypeName, string body)
        {
            iTextSharp.text.Document document   = new iTextSharp.text.Document(PageSize.A4, 88f, 88f, 10f, 10f);
            iTextSharp.text.Font     NormalFont = FontFactory.GetFont("Arial", 11, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.DARK_GRAY);
            try
            {
                string FilePath = Server.MapPath("/Correspondence/" + correspondenceId + "_" + correspondenceTypeName + ".pdf");
                document.Open();

                HtmlToPdf converter = new HtmlToPdf();

                // set converter options

                converter.Options.PdfPageSize        = PdfPageSize.A4;
                converter.Options.PdfPageOrientation = PdfPageOrientation.Portrait;
                //converter.Options.WebPageWidth = webPageWidth;
                //converter.Options.WebPageHeight = webPageHeight;

                // create a new pdf document converting an url
                SelectPdf.PdfDocument doc = converter.ConvertHtmlString(body, null);

                byte[]     pdf = doc.Save();
                FileStream fs  = new FileStream(FilePath, FileMode.OpenOrCreate);
                fs.Write(pdf, 0, pdf.Length);
                fs.Close();
                //doc.Save(FilePath);

                document.Close();
                return(true);
                //}
            }
            catch (Exception ex)
            {
            }
            return(false);
        }
Esempio n. 28
0
        //********************************************************************************************
        // Save PDF
        //********************************************************************************************
        private void SaveSuppPDF(int id)
        {
            try
            {
                var tempFilesFolder = Server.MapPath(ConfigurationManager.AppSettings["TempFilesRoot"]);
                var filename        = id + "_Quote.pdf";
                var fileloc         = tempFilesFolder + "\\";
                var fullPath        = fileloc + filename;

                SelectPdf.HtmlToPdf converter = new SelectPdf.HtmlToPdf();
                string url = Request.Url.Authority + Request.ApplicationPath + "/Quotes/QuoteDetailsSuppPDF/" + id;
                converter.Options.PdfPageSize        = SelectPdf.PdfPageSize.A4;
                converter.Options.PdfPageOrientation = SelectPdf.PdfPageOrientation.Portrait;

                SelectPdf.PdfDocument doc = converter.ConvertUrl(url);

                doc.Save(fullPath);
                doc.Close();
            }
            catch (Exception ex)
            {
                //Elmah.ErrorSignal.FromCurrentContext().Raise(ex);
            }
        }
Esempio n. 29
0
        protected void pdfBtn_Click(object sender, EventArgs e)
        {
            try
            {
                var lbl = string.Format("IndividualTestReport_{0}_{1}", candidateId.Text, batchName.Text);
                //Response.Clear();

                //Response.ContentType = "application/pdf";

                //Response.AddHeader("content-disposition", "attachment;filename="+lbl+".pdf");
                //Response.Cache.SetCacheability(HttpCacheability.NoCache);

                //Response.Buffer = true;



                StringWriter   sw = new StringWriter();
                HtmlTextWriter hw = new HtmlTextWriter(sw);
                Panel1.RenderControl(hw);

                StringReader sr = new StringReader(sw.ToString());

                //GlobalConfig gc = new GlobalConfig();
                //gc.SetPaperSize(PaperKind.A4);
                //gc.SetPaperOrientation(true);



                //byte[] pdfBuf = new SynchronizedPechkin(gc).Convert(sr.ReadToEnd());
                //MemoryStream ms = new MemoryStream(pdfBuf);

                //ms.WriteTo(Response.OutputStream);
                //Response.End();

                string      pdf_page_size = "A4";
                PdfPageSize pageSize      = (PdfPageSize)Enum.Parse(typeof(PdfPageSize),
                                                                    pdf_page_size, true);

                string             pdf_orientation = "Landscape";
                PdfPageOrientation pdfOrientation  =
                    (PdfPageOrientation)Enum.Parse(typeof(PdfPageOrientation),
                                                   pdf_orientation, true);

                //int webPageWidth = 1024;
                //try
                //{
                //    webPageWidth = Convert.ToInt32(TxtWidth.Text);
                //}
                //catch { }

                //int webPageHeight = 0;
                //try
                //{
                //    webPageHeight = Convert.ToInt32(TxtHeight.Text);
                //}
                //catch { }

                // instantiate a html to pdf converter object
                HtmlToPdf converter = new HtmlToPdf();

                // set css media type
                converter.Options.CssMediaType = (HtmlToPdfCssMediaType)Enum.Parse(typeof(HtmlToPdfCssMediaType), "Screen", true);

                // set converter options
                converter.Options.PdfPageSize        = pageSize;
                converter.Options.PdfPageOrientation = pdfOrientation;
                //converter.Options.WebPageWidth = webPageWidth;
                //converter.Options.WebPageHeight = webPageHeight;

                // create a new pdf document converting an url
                SelectPdf.PdfDocument doc = converter.ConvertHtmlString(sr.ReadToEnd());

                // save pdf document
                doc.Save(Response, false, lbl + ".pdf");

                // close pdf document
                doc.Close();
                HttpContext.Current.Response.Flush();
                HttpContext.Current.Response.SuppressContent = true;
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
            catch (Exception ex)
            {
                WSProfile filter = new WSProfile(System.Reflection.Assembly.GetExecutingAssembly().FullName.Split(',')[0], Path.GetFileName(Request.Url.AbsolutePath) + "-" + System.Reflection.MethodBase.GetCurrentMethod().Name, ApplicationType.WebApplication);
                filter.LogError(ex);
            }
        }
Esempio n. 30
0
        private void Save_Click(object sender, RoutedEventArgs e)
        {
            SelectPdf.GlobalProperties.LicenseKey = "xu335vTz9+b19PL05vf+6Pbm9ffo9/To/////w== ";
            TTfileDict.Clear();
            sqlite_conn = SqLite.OpenSQLLiteConnection(sqlite_conn);
            sqlite_cmd  = sqlite_conn.CreateCommand();
            string commandstring = "SELECT * FROM BALLOTDETAILS  WHERE BALLOTID = " + BallotWindow.BallotId + " ORDER BY CANDIDATESLNO";

            sqlite_cmd.CommandText = commandstring;
            SQLiteDataReader oReader = sqlite_cmd.ExecuteReader();

            while (oReader.Read())
            {
                if (string.IsNullOrEmpty(oReader["CANDIDATEPHOTO"].ToString()))
                {
                    TTfileDict.Add(Convert.ToInt32(oReader["DETAILBALLOTID"]),
                                   new CandidateRecord()
                    {
                        BallotID         = Convert.ToInt32(oReader["BALLOTID"].ToString()),
                        CandidateNO      = Convert.ToInt32(oReader["CANDIDATESLNO"]),
                        CandidateNameENG = oReader["CANDIDATENAMEENG"].ToString(),
                        CandidateNameOL  = oReader["CANDIDATENAMEOL"].ToString(),
                        PartyNameENG     = oReader["PARTYAFFILIATIONENG"].ToString(),
                        PartyNameOL      = oReader["PARTYAFFILIATIONOL"].ToString(),
                        CandidatePhoto   = new byte[1],
                        ISNOTA           = Convert.ToInt32(oReader["ISNOTA"]),
                    });
                }

                else
                {
                    TTfileDict.Add(Convert.ToInt32(oReader["DETAILBALLOTID"]),
                                   new CandidateRecord()
                    {
                        BallotID         = Convert.ToInt32(oReader["BALLOTID"].ToString()),
                        CandidateNO      = Convert.ToInt32(oReader["CANDIDATESLNO"]),
                        CandidateNameENG = oReader["CANDIDATENAMEENG"].ToString(),
                        CandidateNameOL  = oReader["CANDIDATENAMEOL"].ToString(),
                        PartyNameENG     = oReader["PARTYAFFILIATIONENG"].ToString(),
                        PartyNameOL      = oReader["PARTYAFFILIATIONOL"].ToString(),
                        CandidatePhoto   = (byte[])oReader["CANDIDATEPHOTO"],
                        // CandidatePhoto = Convert.ToBase64String(oReader["CANDIDATEPHOTO"] as byte[]),
                        ISNOTA = Convert.ToInt32(oReader["ISNOTA"]),
                    });
                }
            }

            oReader.Close();
            sqlite_cmd.Dispose();
            SqLite.CloseSQLLiteConnection(sqlite_conn);

            if (TTfileDict.Values.Count == 0)
            {
                MessageBox.Show("No Candidate  Record Found...");

                return;
            }
            string str = "";
            List <CandidateRecord> candidateLists = new List <CandidateRecord>();

            candidateLists.Clear();
            foreach (KeyValuePair <int, CandidateRecord> candidate in TTfileDict)
            {
                candidateLists.Add(candidate.Value);
            }


            ballotCandidateList.Candidate = candidateLists;

            string exeFile = (new System.Uri(Assembly.GetEntryAssembly().CodeBase)).AbsolutePath;
            string exeDir  = System.IO.Path.GetDirectoryName(exeFile);

            string Directorypath = Directory.GetCurrentDirectory() + "\\images";

            string base64String1 = ConvertImage(Directorypath + "\\eci-logo.png");
            string Imagesrc      = "data:image/jpg;base64," + base64String1;


            string base64String2 = null;
            string Imagesrc2     = null;

            //string Bordername = null;
            // var TemplateInstance=
            if (BallotWindow.strConstType == "Parliamentary")
            {
                base64String2 = ConvertImage(Directorypath + "\\PC.PNG");
                Imagesrc2     = "data:image/jpg;base64," + base64String2;
                BallotTemplatePC TemplateInstance = new BallotTemplatePC
                {
                    Session = new Dictionary <string, object>()
                };
                TemplateInstance.Session.Add("TTfileDict", ballotCandidateList);
                TemplateInstance.Session.Add("Imagesrc", Imagesrc);
                TemplateInstance.Session.Add("Imagesrc2", Imagesrc2);
                TemplateInstance.Session.Add("FontFamily", BallotWindow.selectedfont);
                TemplateInstance.Initialize();
                str = TemplateInstance.TransformText();
                // Bordername = "PC.PNG";
            }
            else
            {
                base64String2 = ConvertImage(Directorypath + "\\AC.PNG");
                Imagesrc2     = "data:image/jpg;base64," + base64String2;
                BallotTemplateAC TemplateInstanceAC = new BallotTemplateAC
                {
                    Session = new Dictionary <string, object>()
                };
                TemplateInstanceAC.Session.Add("TTfileDict", ballotCandidateList);
                TemplateInstanceAC.Session.Add("Imagesrc", Imagesrc);
                TemplateInstanceAC.Session.Add("Imagesrc2", Imagesrc2);
                TemplateInstanceAC.Session.Add("FontFamily", BallotWindow.selectedfont);
                TemplateInstanceAC.Initialize();
                str = TemplateInstanceAC.TransformText();
                // Bordername = "AC.PNG";
            }

            // ConvertHtmlToImage(str);



            /////////////////////////////////////////////////////////////////////////////////////////
            // Intentionally blank page tt file code
            string str1 = "";
            IntentionallyBlankPage TemplateInstance1 = new IntentionallyBlankPage();

            //TemplateInstance1.Session = new Dictionary<string, object>();
            //TemplateInstance1.Session.Add(Imagesrc, Imagesrc);
            //TemplateInstance1.Initialize();
            str1 = TemplateInstance1.TransformText();
            //////////////////////////////////////////////////////////////////////////////////////


            HtmlToPdf converter = new HtmlToPdf();
            string    fullPath  = System.IO.Path.Combine(exeDir, "..\\..\\HtmlEngine\\Select.Html.dep");
            string    filepath  = System.IO.Path.GetFileName(fullPath);

            GlobalProperties.HtmlEngineFullPath = filepath;
            SelectPdf.PdfDocument doc = converter.ConvertHtmlString(str);

            SelectPdf.PdfDocument doc1    = converter.ConvertHtmlString(str1);
            SelectPdf.PdfPage     pdfPage = doc1.Pages[0];
            for (int i = 0; i < doc.Pages.Count; i++)
            {
                if (i % 2 == 1)
                {
                    doc.InsertPage(i, pdfPage);
                }
            }


            SaveFileDialog saveFileDialog = new SaveFileDialog
            {
                DefaultExt       = "pdf",
                Filter           = "Pdf File|*.pdf",
                Title            = "Save Ballot",
                FileName         = "Ballot",
                InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.Desktop)
            };


            if (saveFileDialog.ShowDialog() == true)
            {
                doc.Save(saveFileDialog.FileName);
                doc.Close();
                MessageBox.Show("File Saved...");
            }
            else
            {
                MessageBox.Show("File Not Saved...");
            }
        }