Esempio n. 1
1
        public byte[] Convert(string template)
        {
            byte[]    outPdfBuffer = null;
            HtmlToPdf converter    = new HtmlToPdf();

            converter.Options.CssMediaType = HtmlToPdfCssMediaType.Print;
            //converter.Options.ViewerPreferences.FitWindow = true;
            converter.Options.ViewerPreferences.CenterWindow = true;
            converter.Options.AutoFitHeight      = HtmlToPdfPageFitMode.AutoFit;
            converter.Options.AutoFitWidth       = HtmlToPdfPageFitMode.AutoFit;
            converter.Options.PdfPageSize        = PdfPageSize.A4;
            converter.Options.PdfPageOrientation = PdfPageOrientation.Landscape;
            PdfDocument doc = converter.ConvertHtmlString(template, AppConstants.ConstAppURL);

            outPdfBuffer = doc.Save();
            return(outPdfBuffer);
        }
        private void PdfWrite(string HtmlStream, string FileName)
        {
            // instantiate the html to pdf converter 
            HtmlToPdf converter = new HtmlToPdf();
            SelectPdf.GlobalProperties.HtmlEngineFullPath = "D:\\Visual studio 2013 projects\\EcommerceProject\\MarkDownApplication\\Dependicies\\Select.Html.dep";

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

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

            // close pdf document 
            doc.Close();
        }
        protected void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();

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

            // get conversion result (contains document info from the web page)
            HtmlToPdfResult result = converter.ConversionResult;

            // set the document properties
            doc.DocumentInformation.Title = result.WebPageInformation.Title;
            doc.DocumentInformation.Subject = result.WebPageInformation.Description;
            doc.DocumentInformation.Keywords = result.WebPageInformation.Keywords;

            doc.DocumentInformation.Author = "Select.Pdf Samples";
            doc.DocumentInformation.CreationDate = DateTime.Now;

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

            // close pdf document
            doc.Close();
        }
        protected override void Render(HtmlTextWriter writer)
        {
            if (startConversion)
            {
                // get html of the page
                TextWriter myWriter = new StringWriter();
                HtmlTextWriter htmlWriter = new HtmlTextWriter(myWriter);
                base.Render(htmlWriter);

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

                // create a new pdf document converting the html string of the page
                PdfDocument doc = converter.ConvertHtmlString(
                    myWriter.ToString(), Request.Url.AbsoluteUri);

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

                // close pdf document
                doc.Close();
            }
            else
            {
                // render web page in browser
                base.Render(writer);
            }
        }
        protected void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            // read parameters from webpage
            int delay = 0;
            try
            {
                delay = Convert.ToInt32(TxtDelay.Text);
            }
            catch { }

            int timeout = 0;
            try
            {
                timeout = Convert.ToInt32(TxtTimeout.Text);
            }
            catch { }

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

            // specify the number of seconds the conversion is delayed
            converter.Options.MinPageLoadTime = delay;

            // set the page timeout
            converter.Options.MaxPageLoadTime = timeout;

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

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

            // close pdf document
            doc.Close();
        }
        protected void btnPDF_Click(object sender, EventArgs e)
        {
            string url = @"http://localhost/MobileDeviceManagement/Form.aspx?id=" + formId +"&hideBtn=true";

            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
            PdfDocument doc = converter.ConvertUrl(url);

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

            // close pdf document
            doc.Close();
        }
Esempio n. 7
0
        public void CreatePDF(string r_ID)
        {
            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();

            // create a new pdf document converting an url
            _url = @"C:\selenium_report\test_rail_report_" + r_ID + "\\index.html";
            _savePath = @"C:\selenium_report\" + r_ID + "_report.pdf";
            PdfDocument doc = converter.ConvertUrl(_url);

            // get conversion result (contains document info from the web page)
            HtmlToPdfResult result = converter.ConversionResult;
            // set the document properties
            doc.DocumentInformation.Title = result.WebPageInformation.Title;
            doc.DocumentInformation.Subject = result.WebPageInformation.Description;
            doc.DocumentInformation.Keywords = result.WebPageInformation.Keywords;

            doc.DocumentInformation.Author = "Select.Pdf Samples";
            doc.DocumentInformation.CreationDate = DateTime.Now;
            // save pdf document
            doc.Save(_savePath);
            Console.WriteLine("Report is create");
            // close pdf document
            doc.Close();
            //Attach file & add comment to task ITDQA-471
            YouTrackAPI YouTrackAPI = new YouTrackAPI(_savePath);
            YouTrackAPI.AttachFileToTask();
            YouTrackAPI.AddComments();
        }
        public ActionResult ClientSheetPdf(int id)
        {
            if (!CurUser.HasAccess(AdGroup.ServiceClaimClientAccess, AdGroup.ServiceControler)) RedirectToAction("AccessDenied", "Error");
            HtmlToPdf converter = new HtmlToPdf();

            string url = Url.Action("ClientSheet", new { id = id });
            var leftPartUrl = String.Format("{0}://{1}:{2}", Request.RequestContext.HttpContext.Request.Url.Scheme, Request.RequestContext.HttpContext.Request.Url.Host, Request.RequestContext.HttpContext.Request.Url.Port);
            url = String.Format("{1}{0}", url, leftPartUrl);
            PdfDocument doc = converter.ConvertUrl(url);
            MemoryStream stream = new MemoryStream();
            doc.Save(stream);
            return File(stream.ToArray(), "application/pdf");
        }
Esempio n. 9
0
 private static int ConvertHtmlFiles(string outDir, int start)
 {
     HtmlToPdf converter = new HtmlToPdf();
     DirectoryInfo downloadedMessageInfo = new DirectoryInfo(outDir);
     foreach (FileInfo file in downloadedMessageInfo.GetFiles("*.htm*"))
     {
         var doc = converter.ConvertUrl(file.FullName);
         doc.Save(string.Format("{0}{1:000}.pdf", outDir, start));
         doc.Close();
         file.Delete();
         start++;
     }
     return start;
 }
        protected void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();

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

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

            // close pdf document
            doc.Close();
        }
        protected void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            // read parameters from the webpage
            string htmlString = TxtHtmlCode.Text;
            string baseUrl = TxtBaseUrl.Text;

            string pdf_page_size = DdlPageSize.SelectedValue;
            PdfPageSize pageSize = (PdfPageSize)Enum.Parse(typeof(PdfPageSize),
                pdf_page_size, true);

            string pdf_orientation = DdlPageOrientation.SelectedValue;
            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 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
            PdfDocument doc = converter.ConvertHtmlString(htmlString, baseUrl);

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

            // close pdf document
            doc.Close();
        }
Esempio n. 12
0
 public static void WriteHtmlToPdfStream(string htmlContent, MemoryStream pdfStream)
 {
     try
     {
         HtmlToPdf   converter   = new HtmlToPdf();
         PdfDocument pdfDocument = converter.ConvertHtmlString(htmlContent);
         pdfDocument.Save(pdfStream);
         pdfDocument.Close();
         // reset stream position
         pdfStream.Position = 0;
     }
     catch (Exception ex)
     {
         // log ("An error occurred from Pdf converter: " + ex.Message);
         throw ex;
     }
 }
Esempio n. 13
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 async Task <HttpResponseMessage> MakeAnOrder(int customerId, string discount, int personId)
        {
            var makeAnOrder = new CreateAnOrder();
            await makeAnOrder.CreateOrder(customerId, discount, personId);

            var       guid     = Guid.NewGuid().ToString();
            HtmlToPdf Renderer = new HtmlToPdf();

            Renderer.RenderHtmlAsPdf(makeAnOrder.GetTemplate()).SaveAs(customerId + personId + guid + ".pdf");
            HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.OK);

            response.Content = new StreamContent(new FileStream(customerId + personId + guid + ".pdf", FileMode.Open, FileAccess.Read));
            response.Content.Headers.ContentDisposition          = new System.Net.Http.Headers.ContentDispositionHeaderValue("attachment");
            response.Content.Headers.ContentDisposition.FileName = customerId + personId + guid + ".pdf";
            response.Content.Headers.ContentType = new MediaTypeHeaderValue("application/pdf");
            return(response);
        }
Esempio n. 15
0
        public void ConvertPDF()
        {
            if (sesion == null)
            {
                sesion = SessionDB.start(Request, Response, false, db);
            }


            HtmlToPdf htmlToPdfConverter = new HtmlToPdf();

            htmlToPdfConverter.SerialNumber = "pe3M9PXB-w+nMx9fE-19yUlYuV-hZSFl4Wc-k5CFlpSL-lJeLnJyc-nA==";

            // set PDF page size and orientation
            htmlToPdfConverter.Document.PageSize        = PdfPageSize.A4;
            htmlToPdfConverter.Document.PageOrientation = PdfPageOrientation.Portrait;
            // set PDF page margins
            //htmlToPdfConverter.Document.Margins = new PdfMargins(0);
            htmlToPdfConverter.Document.Margins.Top    = 35;
            htmlToPdfConverter.Document.Margins.Bottom = 35;


            // convert HTML to PDF
            byte[] pdfBuffer = null;

            // convert HTML code
            string htmlCode = HttpUtility.UrlDecode(sesion.vdata["html"], System.Text.Encoding.Default);

            string thisPageUrl = this.ControllerContext.HttpContext.Request.Url.AbsoluteUri;
            string baseUrl     = thisPageUrl.Substring(0, thisPageUrl.Length - "ConstanciaRetencion".Length);

            // convert HTML code to a PDF memory buffer
            pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlCode, baseUrl);

            // send the PDF file to browser
            // FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");
            //fileResult.FileDownloadName = "Formato_Constancia_Retencion.pdf";



            //Write it back to the client
            Response.ContentType = "application/pdf";
            Response.AddHeader("content-disposition", "inline;  filename=ConstanciaRetencion.pdf");
            Response.BinaryWrite(pdfBuffer);

            // return fileResult;
        }
Esempio n. 16
0
        private void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            string file = "Document.pdf";

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

                // set css media type
                converter.Options.CssMediaType = (HtmlToPdfCssMediaType)Enum.Parse(
                    typeof(HtmlToPdfCssMediaType), DdlCssMediaType.SelectedItem.ToString(), true);

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

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

                // close pdf document
                doc.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("Error: {0}", ex.Message),
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            finally
            {
                Cursor = Cursors.Arrow;
            }

            // open generated pdf
            try
            {
                System.Diagnostics.Process.Start(file);
            }
            catch
            {
                MessageBox.Show("Could not open generated pdf document",
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
Esempio n. 17
0
        public string GenerateConsentDocument(int caseid, int companyid, string signpath, bool signed)
        {
            HtmlToPdf htmlPDF = new HtmlToPdf();
            string    path    = string.Empty;
            string    pdfText = GetTemplateDocument(Constants.ConsentType + "_" + companyid);
            var       acc     = _context.Companies.Where(p => p.id == companyid).FirstOrDefault();
            var       cases   = _context.Cases.Include("Patient").Include("Patient.User").Where(x => x.Id == caseid).FirstOrDefault();

            if (acc != null)
            {
                try
                {
                    pdfText = pdfText.Replace("{{CompanyName}}", acc.Name);
                    if (cases != null)
                    {
                        pdfText = pdfText.Replace("{{PatientName}}", cases.Patient.User.FirstName + " " + cases.Patient.User.LastName);
                    }

                    if (!signed)
                    {
                        pdfText = pdfText.Replace("{{Signature}}", ConfigurationManager.AppSettings.Get("LOCAL_PATH") + "\\app_data\\uploads\\" + "blank.png");
                    }
                    else
                    {
                        pdfText = pdfText.Replace("{{Signature}}", signpath);
                    }

                    path = ConfigurationManager.AppSettings.Get("LOCAL_PATH").TrimEnd("\\".ToCharArray()) + "\\app_data\\uploads\\company_" + companyid + "\\case_" + caseid;
                    htmlPDF.OpenHTML(pdfText);
                    if (!Directory.Exists(path))
                    {
                        Directory.CreateDirectory(path);
                    }
                    htmlPDF.SavePDF(@path + "\\Consent_" + acc.Name + ".pdf");
                    htmlPDF = null;
                }
                catch (Exception) { return(""); }
            }
            else
            {
                return("");
            }

            return(path.TrimEnd("\\".ToCharArray()) + "\\Consent_" + acc.Name + ".pdf");
        }
Esempio n. 18
0
        private void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            Cursor = Cursors.WaitCursor;
            string file = "Document.pdf";

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

                // set links options
                converter.Options.InternalLinksEnabled = ChkInternalLinks.Checked;
                converter.Options.ExternalLinksEnabled = ChkExternalLinks.Checked;

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

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

                // close pdf document
                doc.Close();
            }
            catch (Exception ex)
            {
                MessageBox.Show(String.Format("Error: {0}", ex.Message),
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
                return;
            }
            finally
            {
                Cursor = Cursors.Arrow;
            }

            // open generated pdf
            try
            {
                System.Diagnostics.Process.Start(file);
            }
            catch
            {
                MessageBox.Show("Could not open generated pdf document",
                                "Error", MessageBoxButtons.OK, MessageBoxIcon.Error);
            }
        }
        protected void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            // read parameters from the webpage
            string url = TxtUrl.Text;

            string page_layout             = DdlPageLayout.SelectedValue;
            PdfViewerPageLayout pageLayout = (PdfViewerPageLayout)Enum.Parse(
                typeof(PdfViewerPageLayout), page_layout, true);

            string            page_mode = DdlPageMode.SelectedValue;
            PdfViewerPageMode pageMode  = (PdfViewerPageMode)Enum.Parse(
                typeof(PdfViewerPageMode), page_mode, true);

            bool centerWindow    = ChkCenterWindow.Checked;
            bool displayDocTitle = ChkDisplayDocTitle.Checked;
            bool fitWindow       = ChkFitWindow.Checked;
            bool hideMenuBar     = ChkHideMenuBar.Checked;
            bool hideToolbar     = ChkHideToolbar.Checked;
            bool hideWindowUI    = ChkHideWindowUI.Checked;

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

            // set converter options
            converter.Options.ViewerPreferences.CenterWindow    = centerWindow;
            converter.Options.ViewerPreferences.DisplayDocTitle = displayDocTitle;
            converter.Options.ViewerPreferences.FitWindow       = fitWindow;
            converter.Options.ViewerPreferences.HideMenuBar     = hideMenuBar;
            converter.Options.ViewerPreferences.HideToolbar     = hideToolbar;
            converter.Options.ViewerPreferences.HideWindowUI    = hideWindowUI;

            converter.Options.ViewerPreferences.PageLayout            = pageLayout;
            converter.Options.ViewerPreferences.PageMode              = pageMode;
            converter.Options.ViewerPreferences.NonFullScreenPageMode =
                PdfViewerFullScreenExitMode.UseNone;

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

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

            // close pdf document
            doc.Close();
        }
        protected void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            // read parameters from the webpage
            string url = TxtUrl.Text;

            string page_layout = DdlPageLayout.SelectedValue;
            PdfViewerPageLayout pageLayout = (PdfViewerPageLayout)Enum.Parse(
                typeof(PdfViewerPageLayout), page_layout, true);

            string page_mode = DdlPageMode.SelectedValue;
            PdfViewerPageMode pageMode = (PdfViewerPageMode)Enum.Parse(
                typeof(PdfViewerPageMode), page_mode, true);

            bool centerWindow = ChkCenterWindow.Checked;
            bool displayDocTitle = ChkDisplayDocTitle.Checked;
            bool fitWindow = ChkFitWindow.Checked;
            bool hideMenuBar = ChkHideMenuBar.Checked;
            bool hideToolbar = ChkHideToolbar.Checked;
            bool hideWindowUI = ChkHideWindowUI.Checked;

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

            // set converter options
            converter.Options.ViewerPreferences.CenterWindow = centerWindow;
            converter.Options.ViewerPreferences.DisplayDocTitle = displayDocTitle;
            converter.Options.ViewerPreferences.FitWindow = fitWindow;
            converter.Options.ViewerPreferences.HideMenuBar = hideMenuBar;
            converter.Options.ViewerPreferences.HideToolbar = hideToolbar;
            converter.Options.ViewerPreferences.HideWindowUI = hideWindowUI;

            converter.Options.ViewerPreferences.PageLayout = pageLayout;
            converter.Options.ViewerPreferences.PageMode = pageMode;
            converter.Options.ViewerPreferences.NonFullScreenPageMode =
                PdfViewerFullScreenExitMode.UseNone;

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

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

            // close pdf document
            doc.Close();
        }
Esempio n. 21
0
        protected void buttonCreatePdf_Click(object sender, EventArgs e)
        {
            // create the HTML to PDF converter
            HtmlToPdf htmlToPdfConverter = new HtmlToPdf();

            // set a demo serial number
            htmlToPdfConverter.SerialNumber = "YCgJMTAE-BiwJAhIB-EhlWTlBA-UEBRQFBA-U1FOUVJO-WVlZWQ==";

            // set triggering mode; for WaitTime mode set the wait time before convert
            switch (dropDownListTriggeringMode.SelectedValue)
            {
            case "Auto":
                htmlToPdfConverter.TriggerMode = ConversionTriggerMode.Auto;
                break;

            case "WaitTime":
                htmlToPdfConverter.TriggerMode       = ConversionTriggerMode.WaitTime;
                htmlToPdfConverter.WaitBeforeConvert = int.Parse(textBoxWaitTime.Text);
                break;

            case "Manual":
                htmlToPdfConverter.TriggerMode = ConversionTriggerMode.Manual;
                break;

            default:
                htmlToPdfConverter.TriggerMode = ConversionTriggerMode.Auto;
                break;
            }

            // convert the URL to PDF
            byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(textBoxHtmlCode.Text, null);

            // inform the browser about the binary data format
            HttpContext.Current.Response.AddHeader("Content-Type", "application/pdf");

            // let the browser know how to open the PDF document, attachment or inline, and the file name
            HttpContext.Current.Response.AddHeader("Content-Disposition", String.Format("attachment; filename=TriggeringMode.pdf; size={0}",
                                                                                        pdfBuffer.Length.ToString()));

            // write the PDF buffer to HTTP response
            HttpContext.Current.Response.BinaryWrite(pdfBuffer);

            // call End() method of HTTP response to stop ASP.NET page processing
            HttpContext.Current.Response.End();
        }
Esempio n. 22
0
        protected void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            // read parameters from the webpage
            string url = TxtUrl.Text;

            string userPassword  = TxtUserPassword.Text.Trim();
            string ownerPassword = TxtOwnerPassword.Text.Trim();

            bool canAssembleDocument = ChkCanAssembleDocument.Checked;
            bool canCopyContent      = ChkCanCopyContent.Checked;
            bool canEditAnnotations  = ChkCanEditAnnotations.Checked;
            bool canEditContent      = ChkCanEditContent.Checked;
            bool canFillFormFields   = ChkCanFillFormFields.Checked;
            bool canPrint            = ChkCanPrint.Checked;

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

            // set document passwords
            if (!string.IsNullOrEmpty(userPassword))
            {
                converter.Options.SecurityOptions.UserPassword = userPassword;
            }
            if (!string.IsNullOrEmpty(ownerPassword))
            {
                converter.Options.SecurityOptions.OwnerPassword = ownerPassword;
            }

            //set document permissions
            converter.Options.SecurityOptions.CanAssembleDocument = canAssembleDocument;
            converter.Options.SecurityOptions.CanCopyContent      = canCopyContent;
            converter.Options.SecurityOptions.CanEditAnnotations  = canEditAnnotations;
            converter.Options.SecurityOptions.CanEditContent      = canEditContent;
            converter.Options.SecurityOptions.CanFillFormFields   = canFillFormFields;
            converter.Options.SecurityOptions.CanPrint            = canPrint;

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

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

            // close pdf document
            doc.Close();
        }
        protected void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            // read parameters from the webpage
            string url = TxtUrl.Text;

            string userPassword = TxtUserPassword.Text.Trim();
            string ownerPassword = TxtOwnerPassword.Text.Trim();

            bool canAssembleDocument = ChkCanAssembleDocument.Checked;
            bool canCopyContent = ChkCanCopyContent.Checked;
            bool canEditAnnotations = ChkCanEditAnnotations.Checked;
            bool canEditContent = ChkCanEditContent.Checked;
            bool canFillFormFields = ChkCanFillFormFields.Checked;
            bool canPrint = ChkCanPrint.Checked;

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

            // set document passwords
            if (!string.IsNullOrEmpty(userPassword))
            {
                converter.Options.SecurityOptions.UserPassword = userPassword;
            }
            if (!string.IsNullOrEmpty(ownerPassword))
            {
                converter.Options.SecurityOptions.OwnerPassword = ownerPassword;
            }

            //set document permissions
            converter.Options.SecurityOptions.CanAssembleDocument = canAssembleDocument;
            converter.Options.SecurityOptions.CanCopyContent = canCopyContent;
            converter.Options.SecurityOptions.CanEditAnnotations = canEditAnnotations;
            converter.Options.SecurityOptions.CanEditContent = canEditContent;
            converter.Options.SecurityOptions.CanFillFormFields = canFillFormFields;
            converter.Options.SecurityOptions.CanPrint = canPrint;

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

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

            // close pdf document
            doc.Close();
        }
        public ConvertToPdf(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();
            PdfDocument doc;

            var html = toHTML(str);

            //File.WriteAllText(filename + ".html", html.ToString());
            //HtmlToPdf.RenderHtmlAsPdf(html).SaveAs(filename + (i + 1) + ".pdf");
            doc = converter.ConvertHtmlString(html, filename + i + ".pdf");
            doc.Save(filename + i + ".pdf");
            doc.Close();
            //HtmlToPdf.ConvertUrl(filename + (i + 1) + ".html", pdfname + (i + 1) + ".pdf");
        }
Esempio n. 25
0
        public static void ConvertUrlToPdf(string url)
        {
            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();

            // set converter options
            converter.Options.PdfPageSize        = PdfPageSize.A4;
            converter.Options.PdfPageOrientation = PdfPageOrientation.Portrait;

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

            // save pdf document
            doc.Save(null, false, "Sample.pdf");

            // close pdf document
            doc.Close();
        }
Esempio n. 26
0
        public string CreatePdfFile(String htmlString, int orderId, string receiptType)
        {
            // instantiate a html to pdf converter object
            var converter = new HtmlToPdf();

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

            // save pdf document
            doc.Save($"output-{orderId}.{receiptType}.pdf");

            // close pdf document
            doc.Close();

            //Console.WriteLine($"Finished creating PDF for order {orderId}");

            return($"output-{orderId}.{receiptType}.pdf");
        }
Esempio n. 27
0
        public string GetPdf(Contrato contrato)
        {
            var Renderer    = new HtmlToPdf();
            var nomeArquivo = new Random().Next();

            Renderer.RenderHtmlAsPdf("<h1>Contrato de locação residencial</h1>" +
                                     "<br><h4>Locatario: " + contrato.Locatario.Nome + "</h4>" +
                                     "<br><h4>Corretor: " + contrato.Corretor.Nome + "</h4>" +
                                     "<br><h4>Endereço do Imóvel: " + contrato.Imovel.Endereco + ',' + contrato.Imovel.Cidade + ',' + contrato.Imovel.UF + "</h4>" +
                                     "<br><h4>Valor do Aluguel: " + contrato.Imovel.ValorAluguel + "</h4>" +
                                     "<br><br><br><br><br><br><h4>Assinaturas </h4>" +
                                     "<br><h4>" + contrato.Locatario.Nome + ":______________________________ </h4>" +
                                     "<br><h4>" + contrato.Corretor.Nome + ":______________________________</h4>"

                                     + "<style></style>")
            .SaveAs(_hosting.WebRootPath + $"\\Contratos\\{nomeArquivo}.pdf");
            return(nomeArquivo + ".pdf");
        }
        protected void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();

            // set links options
            converter.Options.InternalLinksEnabled = ChkInternalLinks.Checked;
            converter.Options.ExternalLinksEnabled = ChkExternalLinks.Checked;

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

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

            // close pdf document
            doc.Close();
        }
Esempio n. 29
0
        public void Download()
        {
            using (StringWriter sw = new StringWriter())
            {
                var preview = ViewEngineCollection.FindView(this.ControllerContext, "Report", null);
                ViewData.Add("users", GetUsers());
                var vc = new ViewContext(ControllerContext, preview.View, ViewData, TempData, sw);
                preview.View.Render(vc, sw);

                HtmlToPdf   htp = new HtmlToPdf();
                PdfDocument doc = htp.ConvertHtmlString(sw.ToString());
                using (MemoryStream ms = new MemoryStream())
                {
                    doc.Save(System.Web.HttpContext.Current.Response, false, "BPReport.pdf");
                    doc.Close();
                }
            }
        }
Esempio n. 30
0
        protected void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();

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

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

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

            // close pdf document
            doc.Close();
        }
Esempio n. 31
0
        static async Task PrintWithImageFromFile()
        {
            var renderer = new HtmlToPdf();

            renderer.PrintOptions.Title = "My title";

            var path = Path.Combine(Directory.GetCurrentDirectory(), "files", "GitHub_Logo.png");

            var pdf = await renderer.RenderHtmlAsPdfAsync($"<img src=\"{path}\"><h1>Hello world</h1>");

            await pdf.SaveAsAsync("c:\\my.pdf");

            var filePath = await pdf.SaveInTempFolderAsync();

            Console.WriteLine(filePath);

            Console.ReadLine();
        }
Esempio n. 32
0
        public static ActionResult Convert(FormCollection collection)
        {
            HtmlToPdf converter = new HtmlToPdf();

            converter.Options.PdfPageSize        = PdfPageSize.A4;
            converter.Options.PdfPageOrientation = PdfPageOrientation.Portrait;
            converter.Options.WebPageWidth       = 1202;
            converter.Options.WebPageHeight      = 0;
            PdfDocument doc = converter.ConvertUrl(ConversionUrl);

            byte[] pdf = doc.Save();
            doc.Close();

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

            fileResult.FileDownloadName = "Document.pdf";
            return(fileResult);
        }
Esempio n. 33
0
        public ActionResult ClientSheetPdf(int id)
        {
            if (!CurUser.HasAccess(AdGroup.ServiceClaimClientAccess, AdGroup.ServiceControler))
            {
                RedirectToAction("AccessDenied", "Error");
            }
            HtmlToPdf converter = new HtmlToPdf();

            string url         = Url.Action("ClientSheet", new { id = id });
            var    leftPartUrl = String.Format("{0}://{1}:{2}", Request.RequestContext.HttpContext.Request.Url.Scheme, Request.RequestContext.HttpContext.Request.Url.Host, Request.RequestContext.HttpContext.Request.Url.Port);

            url = String.Format("{1}{0}", url, leftPartUrl);
            PdfDocument  doc    = converter.ConvertUrl(url);
            MemoryStream stream = new MemoryStream();

            doc.Save(stream);
            return(File(stream.ToArray(), "application/pdf"));
        }
        protected void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();

            // set links options
            converter.Options.InternalLinksEnabled = ChkInternalLinks.Checked;
            converter.Options.ExternalLinksEnabled = ChkExternalLinks.Checked;

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

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

            // close pdf document
            doc.Close();
        }
        protected void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();

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

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

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

            // close pdf document
            doc.Close();
        }
Esempio n. 36
0
        public async Task <FileResult> RenderAsync()
        {
            var catalogPageModel = new CatalogPageFiltersViewModel()
            {
                Culture      = CultureInfo.CurrentCulture.Name,
                ItemsPerPage = 0
            };
            var catalogModel = await _catalogViewModelService.GetCatalogItems(catalogPageModel, false, true);

            var cc = catalogModel.CatalogItems.FirstOrDefault();

            var html = await _viewRenderService.RenderToStringAsync("Pdf/Catalog", cc);

            var htmlToPdf = new HtmlToPdf();
            var pdf       = await htmlToPdf.RenderHtmlAsPdfAsync(html);

            return(File(pdf.BinaryData, "application/pdf;", "Catalog.pdf"));
        }
Esempio n. 37
0
        public void GetFileReportClass(string id)
        {
            var reports = (from l in _context.Learners
                           join st in _context.StudyProcesses on l.Id equals st.LearnerId
                           where (st.Status == Status.Active && st.LanguageClassId == id)
                           select new
            {
                Index = 1,
                FullName = l.FirstName + " " + l.LastName,
                YearOfBirth = l.Birthday.Year.ToString(),
                Gender = l.Sex == true ? "Name" : "Nữ",
                l.Phone,
                ClassName = _context.LanguageClasses.Where(x => x.Id == id).Single().Name,
                Note = ""
            }).OrderBy(x => x.FullName).ToList();

            int i       = 1;
            var results = new List <ReportViewModel>();

            foreach (var item in reports)
            {
                ReportViewModel reportViewModel = new ReportViewModel()
                {
                    Index       = i,
                    FullName    = item.FullName,
                    ClassName   = item.ClassName,
                    Gender      = item.Gender,
                    Note        = "",
                    Phone       = item.Phone,
                    YearOfBirth = item.YearOfBirth
                };
                results.Add(reportViewModel);
                i++;
            }


            HtmlToPdf Renderer = new HtmlToPdf();

            Renderer.RenderHtmlAsPdf(ReportControl.GetHTMLString(results)).SaveAs("baocaolop.pdf");

            var PDF = Renderer.RenderHtmlAsPdf(ReportControl.GetHTMLString(results), @"C:\Users\Than Hoang\source\repos\LanguageCenterPLC_BE\LanguageCenterPLC\wwwroot\css\");

            PDF.SaveAs("html-with-assets.pdf");
        }
Esempio n. 38
0
        public ActionResult Index(FormCollection fields)
        {
            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();

            try
            {
                // create a new pdf document converting an url
                PdfDocument doc = converter.ConvertUrl(fields["TxtUrl"]);

                // create memory stream to save PDF
                MemoryStream pdfStream = new MemoryStream();

                // save pdf document into a MemoryStream
                doc.Save(pdfStream);

                // reset stream position
                pdfStream.Position = 0;

                // create email message
                MailMessage message = new MailMessage();
                message.From = new MailAddress("*****@*****.**");
                message.To.Add(new MailAddress(fields["TxtEmail"]));
                message.Subject = "SelectPdf Sample - Convert and Email as Attachment";
                message.Body    = "This email should have attached the PDF document " +
                                  "resulted from the conversion of the following url to pdf: " +
                                  fields["TxtUrl"];
                message.Attachments.Add(new Attachment(pdfStream, "Document.pdf"));

                // send email
                new SmtpClient().Send(message);

                // close pdf document
                doc.Close();

                ViewData["Message"] = "Email sent";
            }
            catch (Exception ex)
            {
                ViewData["Message"] = "An error occurred: " + ex.Message;
            }

            return(View());
        }
Esempio n. 39
0
        /// <summary>
        /// This function is used to set the PDF configuration options
        /// 1. Header Settings
        /// 2. Footer Setings
        /// 3. Font Setting
        /// 4. Date time and page number in footer
        /// </summary>
        /// <param name="converter">Object of the SelectPdf class</param>
        public static void ConfigurePDFOptions(ref HtmlToPdf converter)
        {
            // set converter options
            converter.Options.PdfPageSize        = PdfPageSize.A4;
            converter.Options.PdfPageOrientation = PdfPageOrientation.Portrait;
            converter.Options.MarginLeft         = 10;
            converter.Options.MarginRight        = 10;
            converter.Options.MarginTop          = 20;
            converter.Options.MarginBottom       = 20;

            // header settings
            converter.Options.DisplayHeader     = true;
            converter.Header.DisplayOnFirstPage = true;
            converter.Header.DisplayOnOddPages  = true;
            converter.Header.DisplayOnEvenPages = true;
            converter.Header.Height             = 15;

            // Set the sample data in header
            PdfTextSection headerText = new PdfTextSection(4, 0, "Cloud PCR", new Font("Arial", 12));

            headerText.HorizontalAlign = PdfTextHorizontalAlign.Left;
            headerText.VerticalAlign   = PdfTextVerticalAlign.Middle;
            converter.Header.Add(headerText);

            // footer settings
            converter.Options.DisplayFooter     = true;
            converter.Footer.DisplayOnFirstPage = true;
            converter.Footer.DisplayOnOddPages  = true;
            converter.Footer.DisplayOnEvenPages = true;
            converter.Footer.Height             = 20;

            // Set the current datetime in footer
            PdfTextSection footerText = new PdfTextSection(4, 0, DateTime.Now.ToString("dd-MM-yyyy HH:mm"), new Font("Arial", 8));

            footerText.HorizontalAlign = PdfTextHorizontalAlign.Left;
            footerText.VerticalAlign   = PdfTextVerticalAlign.Middle;
            converter.Footer.Add(footerText);

            // Set the page numbers in footer
            footerText = new PdfTextSection(4, 0, "Page: {page_number} of {total_pages}  ", new Font("Arial", 8));
            footerText.HorizontalAlign = PdfTextHorizontalAlign.Right;
            footerText.VerticalAlign   = PdfTextVerticalAlign.Middle;
            converter.Footer.Add(footerText);
        }
Esempio n. 40
0
        /// <summary>
        /// Exports a pdf report of the overall info on the site
        /// Includes a list of my hobbies if selected, list of reason I would like to work here and
        /// Sends a text message if selected
        /// </summary>
        /// <param name="IncludeHobby"></param>
        /// <param name="IncludeReason"></param>
        /// <param name="MobileNumber"></param>
        /// <param name="SendText"></param>
        public FileResult ExportReport(bool IncludeHobby, bool IncludeReason, string MobileNumber, bool SendText)
        {
            string template = "";

            if (IncludeReason || IncludeHobby)
            {
                var webUtility = new DemoUtility();
                var model      = new ExportModel();

                if (IncludeReason)
                {
                    model.Interests = InterestManager.GetInterests(null).ToList();
                }

                if (IncludeHobby)
                {
                    model.Hobbies = AboutMeManager.GetHobbies(null, null, null).ToList();
                }

                template = webUtility.RenderViewToString(this.ControllerContext, "~/Views/Home/ExportTemplate.cshtml", model, false);
            }

            //This would go in the Utilities Project normally
            if (SendText)
            {
                TwilioClient.Init(accountSid, authToken);

                var message = MessageResource.Create(
                    body: "Your Export Is Complete",
                    from: new Twilio.Types.PhoneNumber("+14028107013"),
                    to: new Twilio.Types.PhoneNumber($"+1{MobileNumber.Trim('-')}")
                    );
            }

            var         converter   = new HtmlToPdf();
            PdfDocument pdfDocument = converter.ConvertHtmlString(template);

            byte[] pdfFile = pdfDocument.Save();
            pdfDocument.Close();

            FileResult fileResult = new FileContentResult(pdfFile, "application/pdf");

            return(fileResult);
        }
Esempio n. 41
0
        public ActionResult ConvertHtmlPageToPdf(string targetPreview)
        {
            try
            {
                var sessionId = Session["UserID"];
                int id        = (Int32)sessionId;
                var uiModel   = GetUserDetails(id);
                if (uiModel == null)
                {
                    return(HttpNotFound());
                }
                // get the HTML code of this view
                string htmlToConvert = RenderViewAsString(targetPreview, uiModel);
                if (htmlToConvert == "")
                {
                    return(HttpNotFound());
                }

                // the base URL to resolve relative images and css
                String thisPageUrl = this.ControllerContext.HttpContext.Request.Url.AbsoluteUri;
                String baseUrl     = thisPageUrl.Substring(0, thisPageUrl.Length - "Home/ConvertThisPageToPdf".Length);

                // instantiate the HiQPdf HTML to PDF converter
                HtmlToPdf htmlToPdfConverter = new HtmlToPdf();

                // set PDF page margins
                htmlToPdfConverter.Document.Margins = new PdfMargins(20, 20, 20, 20);

                // set browser width
                htmlToPdfConverter.BrowserWidth = 740;

                // render the HTML code as PDF in memory
                byte[] pdfBuffer = htmlToPdfConverter.ConvertHtmlToMemory(htmlToConvert, baseUrl);

                // send the PDF file to browser
                FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");
                fileResult.FileDownloadName = "Resume.pdf";
                return(fileResult);
            }
            catch (Exception)
            {
                return(HttpNotFound());
            }
        }
        public ActionResult ConvertToPdf(IFormCollection collection)
        {
            HtmlToPdf htmlToPdfConverter = new HtmlToPdf();

            // set a demo serial number
            htmlToPdfConverter.SerialNumber = "YCgJMTAE-BiwJAhIB-EhlWTlBA-UEBRQFBA-U1FOUVJO-WVlZWQ==";

            htmlToPdfConverter.SelectedHtmlElements = new string[] { collection["textBoxImageSelector"] };
            htmlToPdfConverter.HiddenHtmlElements   = new string[] { collection["textBoxImageSelector"] };

            PdfDocument document = null;

            try
            {
                document = htmlToPdfConverter.ConvertUrlToPdfDocument(collection["textBoxUrl"]);

                foreach (HtmlElementInfo htmlImageInfo in htmlToPdfConverter.ConversionInfo.SelectedHtmlElementsInfo)
                {
                    PdfPageRegion imagePdfRegion = htmlImageInfo.PdfRegions[0];
                    PdfPage       imagePdfPage   = document.Pages[imagePdfRegion.PageIndex];

                    // create the image element
                    PdfImage pdfImage = new PdfImage(imagePdfRegion.Rectangle, m_hostingEnvironment.ContentRootPath + @"\wwwroot" + @"\DemoFiles\Images\HiQPdfLogo_Modified.png");
                    pdfImage.ClipRectangle = imagePdfRegion.Rectangle;

                    imagePdfPage.Layout(pdfImage);
                }

                // write the PDF document to a memory buffer
                byte[] pdfBuffer = document.WriteToMemory();

                FileResult fileResult = new FileContentResult(pdfBuffer, "application/pdf");
                fileResult.FileDownloadName = "ReplaceHtmlElements.pdf";

                return(fileResult);
            }
            finally
            {
                if (document != null)
                {
                    document.Close();
                }
            }
        }
Esempio n. 43
0
        public IActionResult CreatePDF(string url, string FileName)
        {
            if (string.IsNullOrEmpty(url))
            {
                return(Content("请上传网址"));
            }

            if (string.IsNullOrEmpty(FileName))
            {
                FileName = "Lexus车库.pdf";
            }
            else
            {
                if (!FileName.Contains(".pdf"))
                {
                    FileName = FileName += ".pdf";
                }
            }
            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();

            // set converter options
            converter.Options.PdfPageSize        = PdfPageSize.A4;
            converter.Options.PdfPageOrientation = PdfPageOrientation.Portrait;
            converter.Options.WebPageWidth       = 1024;
            converter.Options.WebPageHeight      = 0;

            // create a new pdf document converting an url
            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")
            {
                FileDownloadName = FileName
            };

            return(fileResult);
        }
Esempio n. 44
0
        public string Build(string path, string html)
        {
            var pathPDF = "/pdf-nao-gerrado-erro-verifique-o-servidor.pdf";

            try
            {
                //TODO o ideal é enviar para um bucket, porém como é somente um teste ficará no local por enquanto
                pathPDF = $"/Files/File-{DateTime.Now:dd-mm-yyyy}.pdf";
                var renderer = new HtmlToPdf();
                renderer.RenderHtmlAsPdf(html).SaveAs($"{path}/wwwroot{pathPDF}");
            }
            catch (Exception erro)
            {
                Console.WriteLine(erro.Message);
                Console.WriteLine(erro.StackTrace);
            }

            return(pathPDF);
        }
Esempio n. 45
0
        protected void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();

            // set the HTTP cookies
            converter.Options.HttpCookies.Add(TxtName1.Text, TxtValue1.Text);
            converter.Options.HttpCookies.Add(TxtName2.Text, TxtValue2.Text);
            converter.Options.HttpCookies.Add(TxtName3.Text, TxtValue3.Text);
            converter.Options.HttpCookies.Add(TxtName4.Text, TxtValue4.Text);

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

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

            // close pdf document
            doc.Close();
        }
        protected void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            // instantiate a html to pdf converter object
            HtmlToPdf converter = new HtmlToPdf();

            // set the css selectors for the automatic bookmarks
            converter.Options.PdfBookmarkOptions.CssSelectors =
                TxtElements.Text.Split(new char[] { ',' });

            // display the bookmarks when the document is opened in a viewer
            converter.Options.ViewerPreferences.PageMode = PdfViewerPageMode.UseOutlines;

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

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

            // close pdf document
            doc.Close();
        }
Esempio n. 47
0
        protected void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            // read parameters from the webpage
            string htmlString = TxtHtmlCode.Text;
            string baseUrl = TxtBaseUrl.Text;

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

            converter.Options.MarginTop = 10;
            converter.Options.MarginBottom = 10;
            converter.Options.MarginLeft = 10;
            converter.Options.MarginRight = 10;

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

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

            // close pdf document
            doc.Close();
        }
        protected void BtnCreatePdf_Click(object sender, EventArgs e)
        {
            // get parameters
            string headerUrl = Server.MapPath("~/files/header.html");
            string footerUrl = Server.MapPath("~/files/footer.html");

            bool showHeaderOnFirstPage = ChkHeaderFirstPage.Checked;
            bool showHeaderOnOddPages = ChkHeaderOddPages.Checked;
            bool showHeaderOnEvenPages = ChkHeaderEvenPages.Checked;

            int headerHeight = 50;
            try
            {
                headerHeight = Convert.ToInt32(TxtHeaderHeight.Text);
            }
            catch { }

            bool showFooterOnFirstPage = ChkFooterFirstPage.Checked;
            bool showFooterOnOddPages = ChkFooterOddPages.Checked;
            bool showFooterOnEvenPages = ChkFooterEvenPages.Checked;

            int footerHeight = 50;
            try
            {
                footerHeight = Convert.ToInt32(TxtFooterHeight.Text);
            }
            catch { }

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

            // header settings
            converter.Options.DisplayHeader = showHeaderOnFirstPage ||
                showHeaderOnOddPages || showHeaderOnEvenPages;
            converter.Header.DisplayOnFirstPage = showHeaderOnFirstPage;
            converter.Header.DisplayOnOddPages = showHeaderOnOddPages;
            converter.Header.DisplayOnEvenPages = showHeaderOnEvenPages;
            converter.Header.Height = headerHeight;

            PdfHtmlSection headerHtml = new PdfHtmlSection(headerUrl);
            headerHtml.AutoFitHeight = HtmlToPdfPageFitMode.AutoFit;
            converter.Header.Add(headerHtml);

            // footer settings
            converter.Options.DisplayFooter = showFooterOnFirstPage ||
                showFooterOnOddPages || showFooterOnEvenPages;
            converter.Footer.DisplayOnFirstPage = showFooterOnFirstPage;
            converter.Footer.DisplayOnOddPages = showFooterOnOddPages;
            converter.Footer.DisplayOnEvenPages = showFooterOnEvenPages;
            converter.Footer.Height = footerHeight;

            PdfHtmlSection footerHtml = new PdfHtmlSection(footerUrl);
            footerHtml.AutoFitHeight = HtmlToPdfPageFitMode.AutoFit;
            converter.Footer.Add(footerHtml);

            // add page numbering element to the footer
            if (ChkPageNumbering.Checked)
            {
                // page numbers can be added using a PdfTextSection object
                PdfTextSection text = new PdfTextSection(0, 10,
                    "Page: {page_number} of {total_pages}  ",
                    new System.Drawing.Font("Arial", 8));
                text.HorizontalAlign = PdfTextHorizontalAlign.Right;
                converter.Footer.Add(text);
            }

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

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

            // close pdf document
            doc.Close();
        }
Esempio n. 49
0
    private void PrintInvoice(string invoiceNumber)
    {
        int InvoiceId = Conversion.ParseInt(invoiceNumber);
        Invoice objInvoice = new Invoice(InvoiceId);
        string InFavorOf = OrganizationInfo.GetOrgLegalNameByOrgId(objInvoice.Organizationid);

        StringBuilder sb = new StringBuilder();

        sb.Append("<table style=\"background-color: #f6f6f6; width: 100%; font-family: Arial, sans-serif; font-size:13px; line-height:18px; color:#222;\"");

        sb.Append("<tr>");
        sb.Append("<td vertical-align: top;></td>");
        sb.Append("<td vertical-align: top;width=\"600\" style=\"display: block; max-width: 600px; margin: 0 auto; clear: both;\">");

        sb.Append("<div style=\"max-width: 600px; margin: 0 auto; display: block; padding: 20px;\">");

        sb.Append("<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\" style=\"  background: #fff; border: 1px solid #e9e9e9; border-radius: 3px;\">");
        sb.Append("<tr>");

        sb.Append("<td vertical-align: top; style=\"text-align:center; padding:20px;\">");

        sb.Append("<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\">");

        sb.Append("<tr>");
        sb.Append("<td vertical-align: top; style=\"padding:0 0 20px;\">");
        sb.Append(String.Format("<h2 style=\"font-size: 24px; font-weight:normal;\">Invoice No. {0}</h2>", invoiceNumber));
        sb.Append("</td>");
        sb.Append("</tr>");

        sb.Append("<tr>");
        sb.Append("<td vertical-align: top; style=\"padding:0 0 20px;\">");
        sb.Append("<table style=\"margin: 40px auto; text-align: left; width: 80%;\">");
        sb.Append("<tr>");
        sb.Append(String.Format("<td vertical-align: top;>Invoice #101055<br>Invoice Date: {0} <br /> </td>", objInvoice.InvoiceDate.ToShortDateString()));
        sb.Append("</tr>");

        sb.Append("<tr>");
        sb.Append("<td vertical-align: top;>");

        sb.Append("<table width=\"100%\" cellpadding=\"0\" cellspacing=\"0\">");

        sb.Append("<tr>");
        sb.Append("<td vertical-align: top; style=\"border-top: #eee 1px solid; padding: 5px 0;\">To</td>");
        sb.Append(String.Format("<td vertical-align: top; style=\"border-top: #eee 1px solid; padding: 5px 0; text-align:right;\">{0}</td>", objInvoice.OrganizationForName));
        sb.Append("</tr>");

        sb.Append("<tr>");
        sb.Append("<td vertical-align: top; style=\"border-top: #eee 1px solid; padding: 5px 0;\">From</td>");
        sb.Append(String.Format("<td vertical-align: top; style=\"border-top: #eee 1px solid; padding: 5px 0; text-align:right;\">{0}</td>", InFavorOf));
        sb.Append("</tr>");

        sb.Append("<tr>");
        sb.Append("<td vertical-align: top; style=\"border-top: #eee 1px solid; padding: 5px 0;\">Invoice Amount</td>");
        sb.Append(String.Format("<td vertical-align: top; style=\"border-top: #eee 1px solid; padding: 5px 0; text-align:right;\">{0}</td>", objInvoice.InvoiceAmount.ToString("C")));
        sb.Append("</tr>");

        sb.Append("<tr>");
        sb.Append("<td vertical-align: top; style=\"border-top: #eee 1px solid; padding: 5px 0;\">Due Date</td>");
        sb.Append(String.Format("<td vertical-align: top; style=\"border-top: #eee 1px solid; padding: 5px 0; text-align:right;\">{0}</td>", objInvoice.DueDate.ToShortDateString()));
        sb.Append("</tr>");

        //sb.Append("<tr>");
        //sb.Append("<td vertical-align: top; width=\"70%\" style=\"border-top: 2px solid #333; border-bottom: 2px solid #333; font-weight: 700; text-align:right;\">Total</td>");
        //sb.Append(String.Format(" <td vertical-align: top; style=\"border-top: 2px solid #333; border-bottom: 2px solid #333; font-weight: 700; text-align:right;\">{0}</td>","$6.00"));
        //sb.Append("</tr>");

        sb.Append("</table></td</tr></table></td></tr>");

        sb.Append("<tr>");
        sb.Append("<td vertical-align: top; style=\"padding: 0 0 20px;\">");
        sb.Append("EPR Technology Solutions © 2014-2015");

        sb.Append("</td></tr></table></td></tr></table><div></div></div></td><td vertical-align: top;></td></tr></table>");


        HtmlToPdf converter = new HtmlToPdf();

        converter.Options.PdfPageSize = PdfPageSize.A10;
        converter.Options.PdfPageOrientation = PdfPageOrientation.Portrait;

        //PdfDocument doc = converter.ConvertHtmlString(sb.ToString());
        //doc.Save(Response, false, string.Format("{0}.pdf", invoiceNumber));
        //doc.Close();
    }
Esempio n. 50
0
    //protected void gvInvoicesinfo_RowDataBound(object sender, GridViewRowEventArgs e)
    //{
    //    if (e.Row.RowType == DataControlRowType.DataRow)
    //    {
    //        LinkButton imgApproved = (LinkButton)e.Row.FindControl("lnkApproved");
    //        LinkButton imgRejected = (LinkButton)e.Row.FindControl("lnkRejected");
    //        //LinkButton imgPending = (LinkButton)e.Row.FindControl("lnkPending");
    //        //LinkButton imgbtnSend = (LinkButton)e.Row.FindControl("lnkbtnSend");
    //        //LinkButton imgbtnPaid = (LinkButton)e.Row.FindControl("lnkbtnPaid");



    //        if (Conversion.ParseDBNullInt(DataBinder.Eval(e.Row.DataItem, "Organizationid")) == UserOrganizationId)
    //        {
    //            if (Conversion.ParseDBNullBool(DataBinder.Eval(e.Row.DataItem, "IsSent")) == false)
    //            {
    //                imgApproved.Visible = false;
    //                imgRejected.Visible = false;
    //                //imgPending.Visible = true;
    //                //imgbtnSend.Visible = true;
    //                //imgbtnPaid.Visible = false;

    //                //imgbtnEditLoad.Visible = false;


    //            }




    //            //else if (Conversion.ParseDBNullBool(DataBinder.Eval(e.Row.DataItem, "IsSent")) == true)
    //            //{
    //            //    imgApproved.Visible = false;
    //            //    imgRejected.Visible = true;
    //            //    imgPending.Visible = false;
    //            //    imgbtnEditLoad.Visible = false;
    //            //}
    //            //else
    //            //{
    //            //    imgApproved.Visible = false;
    //            //    imgRejected.Visible = false;
    //            //    imgPending.Visible = true;
    //            //}
    //        }
    //        else
    //        {
    //            if (Conversion.ParseDBNullInt(DataBinder.Eval(e.Row.DataItem, "OrganizationForToId")) == UserOrganizationId)
    //            {
    //                //e.Row.BackColor = System.Drawing.Color.LightBlue;
    //                if (Conversion.ParseDBNullBool(DataBinder.Eval(e.Row.DataItem, "IsPaid")) == true)
    //                {
    //                    imgApproved.Visible = true;
    //                    imgRejected.Visible = false;
    //                    //imgPending.Visible = false;
    //                    //imgbtnSend.Visible = false;
    //                    //imgbtnPaid.Visible = false;

    //                }
    //                else
    //                {

    //                    //imgbtnPaid.Visible = true;
    //                }
    //            }

    //        }


    //    }
    //}

    #endregion
    #region Print

    private void PrintDiv(string invoiceNumber)
    {
        string baseUrl = HttpContext.Current.Server.MapPath("/");

        StringBuilder sb = new StringBuilder();

        sb.Append("<table style=\"width: 75%;margin-top: 110px;font-size:xx-large;\" align=\"center\"><tr style=\"width:100%;border-bottom:solid 1px;\">");
        sb.Append(String.Format("<td style=\"width: 50%; border-right: solid 1px; border-bottom: 1px solid; border-left: 1px solid; font-weight: bold; border-top: 1px solid;\">{0} </td>", ResourceMgr.GetMessage("To")));
        sb.Append("<td style=\"width: 50%; border-right: solid 1px; border-bottom: 1px solid;border-top:1px solid;\">");
        sb.Append(lblTo.Text + "</td></tr>");


        sb.Append("<tr style=\"width:100%;border-bottom:solid 1px;\">");
        sb.Append(String.Format("<td style=\"width: 50%; border-right: solid 1px; border-bottom: 1px solid; border-left: 1px solid; font-weight: bold; \">{0}</td>", ResourceMgr.GetMessage("Invoice Number")));
        sb.Append(String.Format("<td style=\"width: 50%; border-right: solid 1px; border-bottom: 1px solid;\">{0}</td>", lblInvoiceNumber.Text));
        sb.Append("</tr>");

        sb.Append("<tr style=\"width:100%;border-bottom:solid 1px;\">");
        sb.Append(String.Format("<td style=\"width: 50%; border-right: solid 1px; border-bottom: 1px solid; border-left: 1px solid; font-weight: bold; \">{0}</td>", ResourceMgr.GetMessage("Invoice Date")));
        sb.Append(String.Format("<td style=\"width: 50%; border-right: solid 1px; border-bottom: 1px solid;\">{0}</td>", lblinvoiceDate.Text));
        sb.Append("</tr>");

        sb.Append("<tr style=\"width:100%;border-bottom:solid 1px;\">");
        sb.Append(String.Format("<td style=\"width: 50%; border-right: solid 1px; border-bottom: 1px solid; border-left: 1px solid; font-weight: bold; \">{0}</td>", ResourceMgr.GetMessage("Invoice Amount")));
        //sb.Append(String.Format("<td style=\"width: 50%; border-right: solid 1px; border-bottom: 1px solid;\">{0}</td>", lblInvoiceAmount.Text));
        sb.Append("</tr>");

        sb.Append("<tr style=\"width:100%;border-bottom:solid 1px;\">");
        sb.Append(String.Format("<td style=\"width: 50%; border-right: solid 1px; border-bottom: 1px solid; border-left: 1px solid; font-weight: bold; \">{0}</td>", ResourceMgr.GetMessage("Due Date")));
        sb.Append(String.Format("<td style=\"width: 50%; border-right: solid 1px; border-bottom: 1px solid;\">{0}</td>", lblDate.Text));
        sb.Append("</tr>");

        sb.Append("</table>");


        HtmlToPdf converter = new HtmlToPdf();

        converter.Options.PdfPageSize = PdfPageSize.A4;
        converter.Options.PdfPageOrientation = PdfPageOrientation.Portrait;

        //PdfDocument doc = converter.ConvertHtmlString(sb.ToString());
        //doc.Save(Response, true, string.Format("{0}.pdf", invoiceNumber));
        //doc.Close();
    }
Esempio n. 51
0
        public ActionResult StatementRestFewHours(StatementRestFewHours data)
        {
            try
            {
                data.Configure();
            }
            catch (Exception ex)
            {
                TempData["ServerError"] = ex.Message;
                return View("StatementFewHours", data);
            }

            HtmlToPdf converter = new HtmlToPdf();
            var statementPrint = new StatementPrint
            {
                IdStatementType = 1,
                EmployeeSid = data.SidEmployee,
                DateBegin = data.HourStart,
                DateEnd = data.HourEnd,
                DurationHours = data.HoursCount,
                Cause = data.Cause,
                IdDepartment = data.Employee.Department.Id,
                IdOrganization = data.Employee.Organization.Id,
                Confirmed = false
            };
            ResponseMessage rm;
            if(statementPrint.Save(out rm))
                statementPrint.Id = rm.Id;
            string url = Url.Action("StatementRestHours", new { sid = data.SidEmployee, dateRest = data.DateRest, hourStart = data.HourStart, hoursCount = data.HoursCount, cause = data.Cause, id = statementPrint.Id});
            var leftPartUrl = String.Format("{0}://{1}:{2}", Request.RequestContext.HttpContext.Request.Url.Scheme, Request.RequestContext.HttpContext.Request.Url.Host, Request.RequestContext.HttpContext.Request.Url.Port);
            url = String.Format("{1}{0}", url, leftPartUrl);
            PdfDocument doc = converter.ConvertUrl(url);
               //     var t = StatementPrint.GetList();

               //         t = StatementPrint.GetList();
            MemoryStream stream = new MemoryStream();
            doc.Save(stream);
            return File(stream.ToArray(), "application/pdf");

            //return View("StatementNoOf", data);
        }
Esempio n. 52
0
        public ActionResult StatementRestFewHours(StatementRestFewHours data)
        {
            try
            {
                data.Configure();
            }
            catch (Exception ex)
            {
                TempData["ServerError"] = ex.Message;
                return View("StatementFewHours", data);
            }

            HtmlToPdf converter = new HtmlToPdf();

            string url = Url.Action("StatementRestHours", new { sid = data.SidEmployee, dateRest = data.DateRest, hourStart = data.HourStart, hoursCount = data.HoursCount, cause = data.Cause });
            var leftPartUrl = String.Format("{0}://{1}:{2}", Request.RequestContext.HttpContext.Request.Url.Scheme, Request.RequestContext.HttpContext.Request.Url.Host, Request.RequestContext.HttpContext.Request.Url.Port);
            url = String.Format("{1}{0}", url, leftPartUrl);
            PdfDocument doc = converter.ConvertUrl(url);
            MemoryStream stream = new MemoryStream();
            doc.Save(stream);
            return File(stream.ToArray(), "application/pdf");

            //return View("StatementNoOf", data);
        }
Esempio n. 53
0
        public ActionResult DocumentEmployeeList()
        {
            var user = DisplayCurUser();
            if (!user.UserCanEdit()) return RedirectToAction("AccessDenied", "Error");

            HtmlToPdf converter = new HtmlToPdf();

            string url = Url.Action("DocEmployeeList");
            var leftPartUrl = String.Format("{0}://{1}:{2}", Request.RequestContext.HttpContext.Request.Url.Scheme, Request.RequestContext.HttpContext.Request.Url.Host, Request.RequestContext.HttpContext.Request.Url.Port);
            url = String.Format("{1}{0}", url, leftPartUrl);
            PdfDocument doc = converter.ConvertUrl(url);
            MemoryStream stream = new MemoryStream();
            doc.Save(stream);
            return File(stream.ToArray(), "application/pdf");

            //return View("DocumentEmployeeList", new DocumentEmployeeList());
        }
Esempio n. 54
0
        public static void SendItBudget()
        {
            HtmlToPdf converter = new HtmlToPdf();
            string url = String.Format("{0}/Report/ItBudgetView", stuffUrl);
            PdfDocument doc = converter.ConvertUrl(url);
            MemoryStream stream = new MemoryStream();
            doc.Save(stream);

            var file = new AttachmentFile() { Data = stream.ToArray(), FileName = "it-budget.pdf", DataMimeType = MediaTypeNames.Application.Pdf };
            //var recipients = new MailAddress[] {new MailAddress("*****@*****.**"), new MailAddress("*****@*****.**"), new MailAddress("*****@*****.**") };
            var recipientsStr = ConfigurationManager.AppSettings["ItBudgetRecipients"].Split('|');
            //string monthName = new TranslitDate().GetMonthName(DateTime.Now.AddMonths(1).Month);
            var recipients = (from s in recipientsStr where !String.IsNullOrEmpty(s) select new MailAddress(s)).ToArray();
            string monthName = TranslitDate.GetMonthNameImenit(DateTime.Now.AddMonths(-1).Month);
            SendMailSmtp(String.Format("ИТ бюджет за {0} {1}", monthName, DateTime.Now.AddMonths(-1).Year), "Добрый день. ИТ бюджет во вложении", true, null, recipients, null, file);
        }
 private HtmlToPdf GetHtmlToPdf(float Bottom, float Top, float Left, float Right)
 {
     HiQPdf.HtmlToPdf docpdf = new HtmlToPdf();
     docpdf.Document.Margins.Bottom = Bottom;
     docpdf.Document.Margins.Top = Top;
     docpdf.Document.Margins.Left = Left;
     docpdf.Document.Margins.Right = Right;
     docpdf.SerialNumber = HIQPDF_SERIAL;
     return docpdf;
 }
Esempio n. 56
-1
        public void Download()
        {
            using (StringWriter sw = new StringWriter())
            {
                var preview = ViewEngineCollection.FindView(this.ControllerContext, "Report", null);
                ViewData.Add("users", GetUsers());
                var vc = new ViewContext(ControllerContext, preview.View, ViewData, TempData, sw);
                preview.View.Render(vc, sw);

                HtmlToPdf htp = new HtmlToPdf();
                PdfDocument doc = htp.ConvertHtmlString(sw.ToString());
                using (MemoryStream ms = new MemoryStream())
                {
                    doc.Save(System.Web.HttpContext.Current.Response, false, "BPReport.pdf");
                    doc.Close();
                }
            }
        }