protected void Page_Load(object sender, EventArgs e) { if (!string.IsNullOrEmpty(Request.QueryString["htmlSource"]) && !string.IsNullOrEmpty(Request.QueryString["pdfOutput"])) { string host_url = Request.QueryString["htmlSource"]; string file_out = string.Format("{0}{1}", Server.MapPath(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["Site_PdfOutput"])), Request.QueryString["pdfOutput"]); var authentication_cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; var sb_parameters = new StringBuilder(); HtmlToPdfConverter converter = new HtmlToPdfConverter(); converter.ConvertFromUrl(host_url, file_out, new HtmlToPdfConverterOptions { Orientation = "portrait", CookieName = authentication_cookie.Name, CookieValue = authentication_cookie.Value }); Response.ContentType = string.Format("application/{0}", Path.GetExtension(file_out).Trim('.')); Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", Path.GetFileName(file_out))); Response.TransmitFile(file_out); Response.Flush(); File.Delete(file_out); } }
private void SetPageSettings(HtmlToPdfConverter pdfConverter) { _pdfConverter.Orientation = PageOrientation.Landscape; _pdfConverter.Size = PageSize.A4; _pdfConverter.Margins.Bottom = 5; _pdfConverter.Margins.Top = 15; _pdfConverter.Margins.Left = 10; _pdfConverter.Margins.Right = 10; }
protected void Page_Load(object sender, EventArgs e) { if (!string.IsNullOrEmpty(Request.QueryString["htmlSource"]) && !string.IsNullOrEmpty(Request.QueryString["pdfOutput"])) { string host_url = Request.QueryString["htmlSource"]; string file_out = string.Format("{0}{1}", Server.MapPath(Convert.ToString(System.Configuration.ConfigurationManager.AppSettings["Site_PdfOutput"])), Request.QueryString["pdfOutput"]); var authentication_cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; var sb_parameters = new StringBuilder(); HtmlToPdfConverter converter = new HtmlToPdfConverter(); converter.ConvertFromUrl(host_url, file_out, new HtmlToPdfConverterOptions { Orientation = "portrait", CookieName = authentication_cookie.Name, CookieValue = authentication_cookie.Value }); // EMAIL PDF int email_id = Convert.ToInt32(System.Configuration.ConfigurationManager.AppSettings["Members_InvitationEmailID"]); string email_address = Convert.ToString(Request.QueryString["emailAddress"]); Quartz.Communication.qCom_EmailTool email = new Quartz.Communication.qCom_EmailTool(email_id); qPtl_User user = new qPtl_User(Convert.ToInt32(Context.Items["UserID"])); email.SendDatabaseMailWithAttachment(email_address, email_id, user.UserID, "", "", "", file_out); string message = "* Email Successfully Sent"; // DELETE FILE //File.Delete(file_out); // REDIRECT if (!String.IsNullOrEmpty(Request.QueryString["returnURL"])) { //Session.Abandon(); //FormsAuthentication.SignOut(); Response.Redirect(Request.QueryString["returnURL"]); } else Response.Redirect("~/qPtl/invitation-email.aspx?message=" + message + "&file=" + file_out); /* Response.ContentType = string.Format("application/{0}", Path.GetExtension(file_out).Trim('.')); Response.AddHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", Path.GetFileName(file_out))); Response.TransmitFile(file_out); Response.Flush(); File.Delete(file_out); */ } }
protected void Page_Load(object sender, EventArgs e) { if (!Page.IsPostBack) { int user_id = Convert.ToInt32(Context.Items["UserID"]); int training_id = Convert.ToInt32(Request.QueryString["TrainingID"]); string file_out = string.Format("{0}\\user_id{1}_training_id{2}.pdf", Server.MapPath("temp"), user_id, training_id); var authentication_cookie = HttpContext.Current.Request.Cookies[FormsAuthentication.FormsCookieName]; var sb_parameters = new StringBuilder(); sb_parameters.AppendFormat("TrainingID={0}", training_id); HtmlToPdfConverter converter = new HtmlToPdfConverter(); string host_url = string.Format("/social/learning/printing/generate-cert-printout.aspx?"+ sb_parameters.ToString()); converter.ConvertFromUrl(host_url, file_out, new HtmlToPdfConverterOptions { Orientation = "landscape", CookieName = authentication_cookie.Name, CookieValue = authentication_cookie.Value }); if (File.Exists(file_out)) { var file_info = new FileInfo(file_out); Response.ContentType = string.Format("application/{0}", Path.GetExtension(file_out).Trim('.')); Response.AppendHeader("Content-Disposition", string.Format("attachment; filename=\"{0}\"", Path.GetFileName(file_out))); Response.AppendHeader("Content-Length", file_info.Length.ToString()); Response.TransmitFile(file_out); Response.End(); File.Delete(file_out); } } }
public ActionResult Registration(int? id) { var workStream = new MemoryStream(); // get the record to which this registation id belongs to using (var session = NHibernateHelper.CreateSessionFactory()) { using (var transaction = session.BeginTransaction()) { // get the html template content var path = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/templates/registration.html"); var htmlContent = System.IO.File.ReadAllText(path); var registrations = new List<Registration>(session.CreateCriteria(typeof (Registration)).List<Registration>()); var r = registrations.FirstOrDefault(x => x.Id == id); // do string replacements to htmlContent here var parsedHtmlContent = htmlContent; // Head details if (r != null) { parsedHtmlContent = Replacement(parsedHtmlContent, "$$BootstrapCss$$", BootstrapCss); parsedHtmlContent = Replacement(parsedHtmlContent, "$$PHERMC_REG_NO$$", r.PhermcRegistrationNumber); parsedHtmlContent = Replacement(parsedHtmlContent, "$$LAST_RENEWAL_DATE$$", r.LastRenewalDate.HasValue ? r.LastRenewalDate.Value.ToString("dd/MM/yyyy") : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$CAC_NUMBER$$", r.CacNumber); parsedHtmlContent = Replacement(parsedHtmlContent, "$$REGISTRATION_DATE$$", r.RegistrationDate.ToString("dd/MM/yyyy")); // Proprietor details parsedHtmlContent = Replacement(parsedHtmlContent, "$$PROPRIETOR_NAME$$", string.Concat(r.ProprietorFirstName, " ", r.ProprietorLastName)); parsedHtmlContent = Replacement(parsedHtmlContent, "$$PROPRIETOR_GENDER_MALE$$", r.ProprietorGender.Equals("Male") ? "X" : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$PROPRIETOR_GENDER_FEMALE$$", r.ProprietorGender.Equals("Female") ? "X" : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$PROPRIETOR_NIN_NUMBER$$", r.ProprietorNinNumber); parsedHtmlContent = Replacement(parsedHtmlContent, "$$PROPRIETOR_MOBILE1$$", r.ProprietorMobile1); parsedHtmlContent = Replacement(parsedHtmlContent, "$$PROPRIETOR_MOBILE2$$", r.ProprietorMobile2); parsedHtmlContent = Replacement(parsedHtmlContent, "$$PROPRIETOR_EMAIL$$", r.ProprietorEmailAddress); parsedHtmlContent = Replacement(parsedHtmlContent, "$$PROPRIETOR_IS_MD_NO$$", !r.ProprietorIsMedicalDirector ? "X" : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$PROPRIETOR_IS_MD_YES$$", r.ProprietorIsMedicalDirector ? "X" : ""); // Medical Director details parsedHtmlContent = Replacement(parsedHtmlContent, "$$MD_NAME$$", string.Concat(r.MedicalDirectorFirstName, " ", r.MedicalDirectorLastName)); parsedHtmlContent = Replacement(parsedHtmlContent, "$$MD_GENDER_MALE$$", r.MedicalDirectorGender == null ? "" : r.MedicalDirectorGender.Equals("Male") ? "X" : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$MD_GENDER_FEMALE$$", r.MedicalDirectorGender == null ? "" : r.MedicalDirectorGender.Equals("Female") ? "X" : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$MD_NIN_NUMBER$$", r.MedicalDirectorNinNumber); parsedHtmlContent = Replacement(parsedHtmlContent, "$$MD_MOBILE1$$", r.MedicalDirectorMobile1); parsedHtmlContent = Replacement(parsedHtmlContent, "$$MD_MOBILE2$$", r.MedicalDirectorMobile2); parsedHtmlContent = Replacement(parsedHtmlContent, "$$MD_EMAIL$$", r.MedicalDirectorEmailAddress); // Establishment details parsedHtmlContent = Replacement(parsedHtmlContent, "$$ESTABLISHMENT_NAME$$", r.EstablishmentName); parsedHtmlContent = Replacement(parsedHtmlContent, "$$ESTABLISHMENT_TYPE_HOSPITAL$$", r.TypeOfEstablishment.Equals("Hospital") ? "X" : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$ESTABLISHMENT_TYPE_CLINIC$$", r.TypeOfEstablishment.Equals("Clinic") ? "X" : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$ESTABLISHMENT_TYPE_LABARATORY$$", r.TypeOfEstablishment.Equals("Laboratory") ? "X" : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$ESTABLISHMENT_TYPE_MATERNITY$$", r.TypeOfEstablishment.Equals("Marernity") ? "X" : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$ESTABLISHMENT_TYPE_PHYSIOTHERAPY$$", r.TypeOfEstablishment.Equals("Physiotherapy") ? "X" : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$ESTABLISHMENT_TYPE_RADIODIAGNOSTIC$$", r.TypeOfEstablishment.Equals("Radiodiagnostic") ? "X" : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$ESTABLISHMENT_TYPE_OTHER$$", r.TypeOfEstablishment.Equals("Other") ? "X" : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$ESTABLISHMENT_TYPE_OTHER_NAME$$", r.TypeOfEstablishment.Equals("Hospital") ? "X" : ""); // Establishment address parsedHtmlContent = Replacement(parsedHtmlContent, "$$ESTABLISHMENT_ADDRESS$$", string.Concat(r.AddressLine1, " ", r.AddressLine2)); parsedHtmlContent = Replacement(parsedHtmlContent, "$$ESTABLISHMENT_LGA$$", r.Lga); parsedHtmlContent = Replacement(parsedHtmlContent, "$$ESTABLISHMENT_LANDMARK$$", r.LandMark); // Numbers of staff /* var staffing = new StringBuilder(); for (var i = 0; i < r.RegistrationStaffing.Count; i++) { var staff = r.RegistrationStaffing[i]; staffing.AppendFormat("{0} {1}", staff.NumberOfStaff, staff.Staffing.Name); if (i >= 0 && i < r.RegistrationStaffing.Count - 1) { staffing.Append(", "); } } parsedHtmlContent = Replacement(parsedHtmlContent, "$$STAFFING_PROFILE$$", staffing.ToString()); */ // Services var services = new StringBuilder(); for (var i = 0; i < r.RegistrationServices.Count; i++) { var service = r.RegistrationServices[i]; services.AppendFormat("{0} {1}", service.Selected, service.Service.Name); if (i >= 0 && i < r.RegistrationServices.Count - 1) { services.Append(", "); } } parsedHtmlContent = Replacement(parsedHtmlContent, "$$SERVICES$$", services.ToString()); // Administrator details parsedHtmlContent = Replacement(parsedHtmlContent, "$$ADMIN_NAME$$", string.Concat(r.AdministratorFirstName, " ", r.AdministratorLastName)); parsedHtmlContent = Replacement(parsedHtmlContent, "$$ADMIN_MOBILE1$$", r.AdministratorMobile1); parsedHtmlContent = Replacement(parsedHtmlContent, "$$ADMIN_MOBILE2$$", r.AdministratorMobile2); // Professional Body details parsedHtmlContent = Replacement(parsedHtmlContent, "$$PBODY_ATT_20$$", r.ProfessionalBodyAttendance.Equals("20 Units") ? "X" : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$PBODY_ATT_LESS20$$", r.ProfessionalBodyAttendance.Equals("Less than 20 Units") ? "X" : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$PBODY_ATT_NOTATALL$$", r.ProfessionalBodyAttendance.Equals("Not at all") ? "X" : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$PBODY_INVOLVE_REGULAR$$", r.ProfessionalBodyInvolvement.Equals("Regular") ? "X" : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$PBODY_INVOLVE_IRREGULAR$$", r.ProfessionalBodyInvolvement.Equals("Irregular") ? "X" : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$PBODY_INVOLVE_NOT$$", r.ProfessionalBodyInvolvement.Equals("Not Involved") ? "X" : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$PBODY_NAME$$", string.Concat(r.ProfessionalBodyFirstName, " ", r.ProfessionalBodyLastName)); parsedHtmlContent = Replacement(parsedHtmlContent, "$$PBODY_POSITION$$", r.ProfessionalBodyPosition); parsedHtmlContent = Replacement(parsedHtmlContent, "$$PBODY_REMARKS$$", r.ProfessionalBodyRemarks); // Acceptance details parsedHtmlContent = Replacement(parsedHtmlContent, "$$ACCEPTANCE_NO$$", !r.AcceptanceDetailsAccepted ? "X" : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$ACCEPTANCE_YES$$", r.AcceptanceDetailsAccepted ? "X" : ""); parsedHtmlContent = Replacement(parsedHtmlContent, "$$ACCEPTANCE_REASON$$", r.AcceptanceDetailsReason); // create instance of pdf api var htmlToPdf = new HtmlToPdfConverter(); // convert theget a byte array var pdfBytes = htmlToPdf.GeneratePdf(parsedHtmlContent); var byteInfo = pdfBytes; workStream.Write(byteInfo, 0, byteInfo.Length); workStream.Position = 0; } } } //return new FileStreamResult(workStream, "application/pdf"); return File(workStream, "application/pdf", string.Format("Establishment_{0}_{1}.pdf", id, DateTime.Now.ToString("yyyyMMddhhmmss")) ); }
private async Task <byte[]> PdfConverter(string fileName) { //html = "<div class='col-sm-12'><img src='" + Request.Url.AbsoluteUri.Replace(Request.Url.AbsolutePath, "") + // "/Images/Barcode-ObservationConsultation.jpg' height='70' width='126' style='float:right'/><div style='clear:both'></div></div>" + html; string viewHtml = string.Empty; viewHtml = await _viewRenderService.RenderViewToStringAsync(this.ControllerContext, "LoanApplication", new LoanViewModel(), TempData); string applicationFormFilePath = _applicationFormDirectorypath + "/" + fileName; string applicationFormOutputFilePath = _applicationFormDirectorypath + "/Generated_" + fileName; if (!Directory.Exists(_applicationFormDirectorypath)) { Directory.CreateDirectory(_applicationFormDirectorypath); } System.IO.File.WriteAllText(applicationFormFilePath, viewHtml, Encoding.UTF8); //var headerText = "<br/><b>" + patient.SName + ", " + patient.FName + "</b> PAS No: " + patient.PasNo + " DOB: " + (string.IsNullOrEmpty(patient.DOB) ? "N/A" : dob.ToString("dd/MM/yyyy")) + (string.IsNullOrEmpty(patient.NHS_No) ? "" : " NHS No :" + patient.NHS_No); byte[] convertedPdfBytes; try { var pdfConverter = new HtmlToPdfConverter { //PageHeaderHtml = "", Orientation = PageOrientation.Portrait, LowQuality = false, Margins = new PageMargins { Bottom = 20, Left = 10, Right = 10, Top = 20 }, //PageFooterHtml = // "<center><small>Generated by Our Clinic Report Generator on " + DateTime.Now.ToString("dd MMMM yyyy HH:mm:ss") + "<span class='page'></span>" + //"</center></small>" }; //pdfConverter.PageHeaderHtml = headerText + "<div style='vertical-align: middle; font-size: 12px;font-weight:bold; color: #fff;background-color:#007fff;margin: 20px 0px 10px 0px; padding: 5px 5px;float:right'>Page <b class='page'></b> of <b class='topage'></b></div><div style='clear:both;'></div>"; convertedPdfBytes = pdfConverter.GeneratePdfFromFile(applicationFormFilePath, null);//Creates pdf very quickly from html file than content itself System.IO.File.WriteAllBytes(_applicationFormDirectorypath + "/ " + Path.GetFileNameWithoutExtension(fileName) + ".pdf", convertedPdfBytes); //if (!ignoreDownload) //{ // Response.Clear(); // var ms = new MemoryStream(convertedPdfBytes); // Response.ContentType = "application/pdf"; // Response.AddHeader("Refresh", "3;URL=/Clinic/ClinicPatientManager.aspx"); // Response.AddHeader("content-disposition", "attachment;filename=PatientClinicalInfo_" + Path.GetFileNameWithoutExtension(fileName) + ".pdf"); // Response.Buffer = true; // ms.WriteTo(Response.OutputStream); // Response.End(); //} } catch (Exception ex) { convertedPdfBytes = null; } return(convertedPdfBytes); }
public ActionResult ConvertHtmlToPdf(IFormCollection collection) { // Create a HTML to PDF converter object with default settings HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(); // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish htmlToPdfConverter.ConversionDelay = 2; // Html Viewer Options // Set HTML Viewer width in pixels which is the equivalent in converter of the browser window width // This is a preferred width of the browser but the actual HTML content width can be larger in case the HTML page // cannot be entirely displayed in the given viewer width // This property gives the size of the HTML content which can be further scaled to fit the PDF page based on selected options // The HTML content size is in pixels and the PDF page size is in points (1 point = 1/72 inches) // The converter is using a 96 DPI resolution to transform pixels to points with the following formula: Points = Pixels/96 * 72 htmlToPdfConverter.HtmlViewerWidth = int.Parse(collection["htmlViewerWidthTextBox"]); // Set HTML viewer height in pixels to convert the top part of a HTML page // Leave it not set to convert the entire HTML if (collection["htmlViewerHeightTextBox"][0].Length > 0) { htmlToPdfConverter.HtmlViewerHeight = int.Parse(collection["htmlViewerHeightTextBox"]); } // Set the HTML content clipping option to force the HTML content width to be exactly HtmlViewerWidth pixels // If this option is false then the actual HTML content width can be larger than HtmlViewerWidth pixels in case the HTML page // cannot be entirely displayed in the given viewer width // By default this option is false and the HTML content is not clipped htmlToPdfConverter.ClipHtmlView = collection["clipContentCheckBox"].Count > 0; // Set the HTML content zoom percentage similar to zoom level in a browser htmlToPdfConverter.HtmlViewerZoom = int.Parse(collection["htmlViewerZoomTextBox"]); // PDF Page Options // Set PDF page size which can be a predefined size like A4 or a custom size in points // Leave it not set to have a default A4 PDF page htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = SelectedPdfPageSize(collection["pdfPageSizeDropDownList"]); // Set PDF page orientation to Portrait or Landscape // Leave it not set to have a default Portrait orientation for PDF page htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = SelectedPdfPageOrientation(collection["pdfPageOrientationDropDownList"]); // Set PDF page margins in points or leave them not set to have a PDF page without margins htmlToPdfConverter.PdfDocumentOptions.LeftMargin = float.Parse(collection["leftMarginTextBox"]); htmlToPdfConverter.PdfDocumentOptions.RightMargin = float.Parse(collection["rightMarginTextBox"]); htmlToPdfConverter.PdfDocumentOptions.TopMargin = float.Parse(collection["topMarginTextBox"]); htmlToPdfConverter.PdfDocumentOptions.BottomMargin = float.Parse(collection["bottomMarginTextBox"]); // HTML Content Destination and Spacing Options // Set HTML content destination in PDF page if (collection["xLocationTextBox"][0].Length > 0) { htmlToPdfConverter.PdfDocumentOptions.X = float.Parse(collection["xLocationTextBox"]); } if (collection["yLocationTextBox"][0].Length > 0) { htmlToPdfConverter.PdfDocumentOptions.Y = float.Parse(collection["yLocationTextBox"]); } if (collection["contentWidthTextBox"][0].Length > 0) { htmlToPdfConverter.PdfDocumentOptions.Width = float.Parse(collection["contentWidthTextBox"]); } if (collection["contentHeightTextBox"][0].Length > 0) { htmlToPdfConverter.PdfDocumentOptions.Height = float.Parse(collection["contentHeightTextBox"]); } // Set HTML content top and bottom spacing or leave them not set to have no spacing for the HTML content htmlToPdfConverter.PdfDocumentOptions.TopSpacing = float.Parse(collection["topSpacingTextBox"]); htmlToPdfConverter.PdfDocumentOptions.BottomSpacing = float.Parse(collection["bottomSpacingTextBox"]); // Scaling Options // Use this option to fit the HTML content width in PDF page width // By default this property is true and the HTML content can be resized to fit the PDF page width htmlToPdfConverter.PdfDocumentOptions.FitWidth = collection["fitWidthCheckBox"].Count > 0; // Use this option to enable the HTML content stretching when its width is smaller than PDF page width // This property has effect only when FitWidth option is true // By default this property is false and the HTML content is not stretched htmlToPdfConverter.PdfDocumentOptions.StretchToFit = collection["stretchCheckBox"].Count > 0; // Use this option to automatically dimension the PDF page to display the HTML content unscaled // This property has effect only when the FitWidth property is false // By default this property is true and the PDF page is automatically dimensioned when FitWidth is false htmlToPdfConverter.PdfDocumentOptions.AutoSizePdfPage = collection["autoSizeCheckBox"].Count > 0; // Use this option to fit the HTML content height in PDF page height // If both FitWidth and FitHeight are true then the HTML content will resized if necessary to fit both width and height // preserving the aspect ratio at the same time // By default this property is false and the HTML content is not resized to fit the PDF page height htmlToPdfConverter.PdfDocumentOptions.FitHeight = collection["fitHeightCheckBox"].Count > 0; // Use this option to render the whole HTML content into a single PDF page // The PDF page size is limited to 14400 points // By default this property is false htmlToPdfConverter.PdfDocumentOptions.SinglePage = collection["singlePageCheckBox"].Count > 0; string url = collection["urlTextBox"]; // Convert the HTML page to a PDF document using the scaling options byte[] outPdfBuffer = htmlToPdfConverter.ConvertUrl(url); // Send the PDF file to browser FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf"); fileResult.FileDownloadName = "HTML_Content_Scaling.pdf"; return(fileResult); }
protected void convertToPdfButton_Click(object sender, EventArgs e) { // Create a HTML to PDF converter object with default settings HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(); // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish htmlToPdfConverter.ConversionDelay = 2; // Set the PDF file to be inserted before conversion result string pdfFileBefore = Server.MapPath("~/DemoAppFiles/Input/PDF_Files/Merge_Before_Conversion.pdf"); htmlToPdfConverter.PdfDocumentOptions.AddStartDocument(pdfFileBefore, addHeaderFooterInInsertedPdfCheckBox.Checked, showHeaderInFirstPageCheckBox.Checked, showFooterInFirstPageCheckBox.Checked); // Set the PDF file to be added after conversion result string pdfFileAfter = Server.MapPath("~/DemoAppFiles/Input/PDF_Files/Merge_After_Conversion.pdf"); htmlToPdfConverter.PdfDocumentOptions.AddEndDocument(pdfFileAfter, addHeaderFooterInAppendedPdfCheckBox.Checked, true, true); // Enable header in the generated PDF document htmlToPdfConverter.PdfDocumentOptions.ShowHeader = true; // Draw header elements if (htmlToPdfConverter.PdfDocumentOptions.ShowHeader) { DrawHeader(htmlToPdfConverter, true); } // Enable footer in the generated PDF document htmlToPdfConverter.PdfDocumentOptions.ShowFooter = true; // Draw footer elements if (htmlToPdfConverter.PdfDocumentOptions.ShowFooter) { DrawFooter(htmlToPdfConverter, true, true); } string url = urlTextBox.Text; // Convert the HTML page to a PDF document and add the external PDF documents byte[] outPdfBuffer = htmlToPdfConverter.ConvertUrl(url); // Send the PDF as response to browser // Set response content type Response.AddHeader("Content-Type", "application/pdf"); // Instruct the browser to open the PDF file as an attachment or inline Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Header_Footer_in_External_PDF.pdf; size={0}", outPdfBuffer.Length.ToString())); // Write the PDF document buffer to HTTP response Response.BinaryWrite(outPdfBuffer); // End the HTTP response and stop the current page processing Response.End(); }
protected void convertToPdfButton_Click(object sender, EventArgs e) { // Get the server IP and port String serverIP = textBoxServerIP.Text; uint serverPort = uint.Parse(textBoxServerPort.Text); // Create a HTML to PDF converter object with default settings HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(serverIP, serverPort); // Set optional service password if (textBoxServicePassword.Text.Length > 0) { htmlToPdfConverter.ServicePassword = textBoxServicePassword.Text; } // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish htmlToPdfConverter.ConversionDelay = 2; // Add custom HTTP headers if (header1NameTextBox.Text.Length > 0 && header1ValueTextBox.Text.Length > 0) { htmlToPdfConverter.HttpRequestHeaders.Add(header1NameTextBox.Text, header1ValueTextBox.Text); } if (header2NameTextBox.Text.Length > 0 && header2ValueTextBox.Text.Length > 0) { htmlToPdfConverter.HttpRequestHeaders.Add(header2NameTextBox.Text, header2ValueTextBox.Text); } if (header3NameTextBox.Text.Length > 0 && header3ValueTextBox.Text.Length > 0) { htmlToPdfConverter.HttpRequestHeaders.Add(header3NameTextBox.Text, header3ValueTextBox.Text); } if (header4NameTextBox.Text.Length > 0 && header4ValueTextBox.Text.Length > 0) { htmlToPdfConverter.HttpRequestHeaders.Add(header4NameTextBox.Text, header4ValueTextBox.Text); } if (header5NameTextBox.Text.Length > 0 && header5ValueTextBox.Text.Length > 0) { htmlToPdfConverter.HttpRequestHeaders.Add(header5NameTextBox.Text, header5ValueTextBox.Text); } // Convert the HTML page to a PDF document in a memory buffer byte[] outPdfBuffer = htmlToPdfConverter.ConvertUrl(urlTextBox.Text); // Send the PDF as response to browser // Set response content type Response.AddHeader("Content-Type", "application/pdf"); // Instruct the browser to open the PDF file as an attachment or inline Response.AddHeader("Content-Disposition", String.Format("attachment; filename=HTTP_Headers.pdf; size={0}", outPdfBuffer.Length.ToString())); // Write the PDF document buffer to HTTP response Response.BinaryWrite(outPdfBuffer); // End the HTTP response and stop the current page processing Response.End(); }
private void button7_Click(object sender, EventArgs e) { SaveFileDialog MyFiles = new SaveFileDialog(); MyFiles.Filter = "PDF File (*.pdf)|*.pdf|HTML File (*.html)|*.html"; MyFiles.Title = "Save As..."; MyFiles.DefaultExt = "*.pdf"; MyFiles.FileName = ReportCombo.Text.Replace(" ", "_").Replace("/", ""); ; if (MyFiles.ShowDialog() == DialogResult.OK) { string name = MyFiles.FileName; string ext = Path.GetExtension(name); if (string.Compare(".pdf",ext,true)==0) { HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(); htmlToPdfConverter.LicenseKey = "sjwvPS4uPSskPSgzLT0uLDMsLzMkJCQk"; htmlToPdfConverter.HtmlViewerWidth = 850; htmlToPdfConverter.PdfDocumentOptions.AvoidImageBreak = true; htmlToPdfConverter.ConvertHtmlToFile(winFormHtmlEditor1.DocumentHtml, "", name); } else { File.WriteAllText(name, winFormHtmlEditor1.DocumentHtml); } } }
protected void convertToPdfButton_Click(object sender, EventArgs e) { // Get the server IP and port String serverIP = textBoxServerIP.Text; uint serverPort = uint.Parse(textBoxServerPort.Text); // Create a HTML to PDF converter object with default settings HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(serverIP, serverPort); // Set optional service password if (textBoxServicePassword.Text.Length > 0) { htmlToPdfConverter.ServicePassword = textBoxServicePassword.Text; } // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish htmlToPdfConverter.ConversionDelay = 2; // Convert a HTML page to a PDF document object Document pdfDocument = htmlToPdfConverter.ConvertUrlToPdfDocumentObject(urlTextBox.Text); // Get the stamp width and height float stampWidth = float.Parse(stampWidthTextBox.Text); float stampHeight = float.Parse(stampHeightTextBox.Text); // Center the stamp at the top of PDF page float stampXLocation = (pdfDocument.GetPage(0).PageSize.Width - stampWidth) / 2; float stampYLocation = 0; // Create the stamp template to be repeated in each PDF page Template stampTemplate = pdfDocument.AddTemplate(stampXLocation, stampYLocation, stampWidth, stampHeight); // Create the HTML element to add in stamp template HtmlToPdfElement stampHtmlElement = new HtmlToPdfElement(htmlStringTextBox.Text, baseUrlTextBox.Text); // Set the HTML viewer width for the HTML added in stamp stampHtmlElement.HtmlViewerWidth = 600; // Fit the HTML content in stamp template stampHtmlElement.FitWidth = true; stampHtmlElement.FitHeight = true; // Add HTML to stamp template stampTemplate.AddElement(stampHtmlElement); // Save the PDF document in a memory buffer byte[] outPdfBuffer = pdfDocument.Save(); // Send the PDF as response to browser // Set response content type Response.AddHeader("Content-Type", "application/pdf"); // Instruct the browser to open the PDF file as an attachment or inline Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Watermarks_and_Stamps.pdf; size={0}", outPdfBuffer.Length.ToString())); // Write the PDF document buffer to HTTP response Response.BinaryWrite(outPdfBuffer); // End the HTTP response and stop the current page processing Response.End(); }
public ActionResult ConvertHtmlToPdf(IFormCollection collection) { // Create a HTML to PDF converter object with default settings HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(); // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish htmlToPdfConverter.ConversionDelay = 2; Document pdfDocument = null; try { // Convert HTML page or string with mapping attributes to a PDF document object // The document can be further modified to highlight the selected elements if (collection["HtmlPageSource"] == "convertHtmlRadioButton") { string htmlWithMappingAttributes = collection["htmlStringTextBox"]; string baseUrl = collection["baseUrlTextBox"]; // Convert a HTML string with mapping attributes to a PDF document object pdfDocument = htmlToPdfConverter.ConvertHtmlToPdfDocumentObject(htmlWithMappingAttributes, baseUrl); } else { string url = collection["urlTextBox"]; // Convert a HTML page with mapping attributes to a PDF document object pdfDocument = htmlToPdfConverter.ConvertUrlToPdfDocumentObject(url); } // Display detailed information about the selected elements StringBuilder htmlElementInfoBuilder = new StringBuilder(); foreach (HtmlElementMapping htmlElementInfo in htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult) { // Get other information about HTML element string htmlElementTagName = htmlElementInfo.HtmlElementTagName; string htmlElementID = htmlElementInfo.HtmlElementId; string htmlElementMappingID = htmlElementInfo.MappingId; string htmlElementCssClasssName = htmlElementInfo.HtmlElementCssClassName; string htmlElementHtmlCode = htmlElementInfo.HtmlElementOuterHtml; string htmlElementInnerHtml = htmlElementInfo.HtmlElementInnerHtml; string htmlElementText = htmlElementInfo.HtmlElementText; System.Collections.Specialized.NameValueCollection htmlElementAttributes = htmlElementInfo.HtmlElementAttributes; HtmlElementPdfRectangle[] htmlElementRectanglesInPdf = htmlElementInfo.PdfRectangles; htmlElementInfoBuilder.AppendFormat("<br/>---------------------------------------- HTML Element Info ----------------------------------------<br/><br/>"); htmlElementInfoBuilder.AppendFormat("<b>Tag Name:</b> {0}<br/>", htmlElementTagName); htmlElementInfoBuilder.AppendFormat("<b>Element ID:</b> {0}<br/>", htmlElementID); htmlElementInfoBuilder.AppendFormat("<b>Mapping ID:</b> {0}<br/>", htmlElementMappingID); htmlElementInfoBuilder.AppendFormat("<b>Text:</b> {0}<br/>", htmlElementText); htmlElementInfoBuilder.AppendFormat("<b>Attributes:</b><br/>"); for (int i = 0; i < htmlElementAttributes.Count; i++) { htmlElementInfoBuilder.AppendFormat(" {0} = \"{1}\"<br/>", htmlElementAttributes.GetKey(i), htmlElementAttributes.Get(i)); } htmlElementInfoBuilder.AppendFormat("<b>Location in PDF:</b><br/>"); for (int i = 0; i < htmlElementRectanglesInPdf.Length; i++) { PdfPage pdfPage = htmlElementRectanglesInPdf[i].PdfPage; int pdfPageIndex = htmlElementRectanglesInPdf[i].PageIndex; RectangleF rectangleInPdfPage = htmlElementRectanglesInPdf[i].Rectangle; htmlElementInfoBuilder.AppendFormat(" PDF Page Index: {0}<br>", pdfPageIndex); htmlElementInfoBuilder.AppendFormat(" Rectangle: X = {0:N2} pt , Y = {1:N2} pt , W = {2:N2} pt , H = {3:N2} pt<br/>", rectangleInPdfPage.X, rectangleInPdfPage.Y, rectangleInPdfPage.Width, rectangleInPdfPage.Height); } htmlElementInfoBuilder.AppendFormat("<br/>"); } PdfPage lastPdfPage = htmlToPdfConverter.ConversionSummary.LastPdfPage; RectangleF lastPageRectangle = htmlToPdfConverter.ConversionSummary.LastPageRectangle; HtmlToPdfElement htmlElementInfoHtml = new HtmlToPdfElement(0, lastPageRectangle.Bottom + 1, htmlElementInfoBuilder.ToString(), null); lastPdfPage.AddElement(htmlElementInfoHtml); // Save the PDF document in a memory buffer byte[] outPdfBuffer = pdfDocument.Save(); // Send the PDF file to browser FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf"); fileResult.FileDownloadName = "Select_in_HTML_Elements_to_Retrieve.pdf"; return(fileResult); } finally { // Close the PDF document if (pdfDocument != null) { pdfDocument.Close(); } } }
public ActionResult ReceiptX(int? id) { var workStream = new MemoryStream(); // get the record to which this registation id belongs to using (var session = NHibernateHelper.CreateSessionFactory()) { using (var transaction = session.BeginTransaction()) { // get the html template content var path = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/templates/receipt.html"); var htmlContent = System.IO.File.ReadAllText(path); var registrations = new List<Registration>(session.CreateCriteria(typeof(Registration)).List<Registration>()); var r = registrations.FirstOrDefault(x => x.Id == id); // do string replacements to htmlContent here var parsedHtmlContent = htmlContent; // Head details if (r != null) { parsedHtmlContent = Replacement(parsedHtmlContent, "$$BootstrapCss$$", BootstrapCss); parsedHtmlContent = Replacement(parsedHtmlContent, "$$PHERMC_REG_NO$$", r.PhermcRegistrationNumber); parsedHtmlContent = Replacement(parsedHtmlContent, "$$LAST_RENEWAL_DATE$$", r.LastRenewalDate.Value.ToString("dd/MM/yyyy")); parsedHtmlContent = Replacement(parsedHtmlContent, "$$CAC_NUMBER$$", r.CacNumber); parsedHtmlContent = Replacement(parsedHtmlContent, "$$REGISTRATION_DATE$$", r.RegistrationDate.ToString("dd/MM/yyyy")); // create $$TBODY_CONTENT$$ here var totalPaid = 0.0M; var tbodyRows = new StringBuilder(); var payments = new List<Payment>(session.CreateCriteria(typeof(Payment)).List<Payment>()); var paymentEntries = from x in payments where x.Registration.Id == id select x; if (paymentEntries.Any()) { foreach (var p in paymentEntries) { totalPaid += p.AmountPaid; } } var lastPayment = paymentEntries.LastOrDefault(); tbodyRows.Append("<tr>"); tbodyRows.AppendFormat("<td>{0}</td>", lastPayment.Created.ToString("dd/MM/yyyy")); tbodyRows.AppendFormat("<td>{0}</td>", lastPayment.PaymentMethod); tbodyRows.AppendFormat("<td>{0}</td>", lastPayment.ReferenceNumber); tbodyRows.AppendFormat("<td>{0}</td>", lastPayment.ReceivedFrom); tbodyRows.AppendFormat("<td>{0}</td>", lastPayment.ReceivedByName); tbodyRows.AppendFormat("<td class=\"right\">₦{0}</td>", lastPayment.AmountPaid.ToString("#,##0.00")); tbodyRows.Append("</tr>"); parsedHtmlContent = Replacement(parsedHtmlContent, "$$TBODY_CONTENT$$", tbodyRows.ToString()); // Update totals parsedHtmlContent = Replacement(parsedHtmlContent, "$$TOTAL$$", lastPayment.AmountPaid.ToString("N2")); parsedHtmlContent = Replacement(parsedHtmlContent, "$$TOTAL_DUE$$", r.RegistrationCosts.ToString("#,##0.00")); var amountOutstanding = r.RegistrationCosts - totalPaid; parsedHtmlContent = Replacement(parsedHtmlContent, "$$OUTSTANDING$$", amountOutstanding.ToString("#,##0.00")); // create instance of pdf api var htmlToPdf = new HtmlToPdfConverter(); // convert theget a byte array var pdfBytes = htmlToPdf.GeneratePdf(parsedHtmlContent); var byteInfo = pdfBytes; workStream.Write(byteInfo, 0, byteInfo.Length); workStream.Position = 0; } } } return new FileStreamResult(workStream, "application/pdf"); }
protected void convertToPdfButton_Click(object sender, EventArgs e) { // Get the server IP and port String serverIP = textBoxServerIP.Text; uint serverPort = uint.Parse(textBoxServerPort.Text); // Create a HTML to PDF converter object with default settings HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(serverIP, serverPort); // Set optional service password if (textBoxServicePassword.Text.Length > 0) { htmlToPdfConverter.ServicePassword = textBoxServicePassword.Text; } // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set the conversion triggering mode if (autoRadioButton.Checked) { // Set Auto triggering mode htmlToPdfConverter.TriggeringMode = TriggeringMode.Auto; } else if (delayedRadioButton.Checked) { // Set delayed triggering moe htmlToPdfConverter.ConversionDelay = int.Parse(conversionDelayTextBox.Text); } else if (manualRadioButton.Checked) { // Set manual triggering mode // The conversion starts when the evoPdfConverter.startConversion() is called // in JavaScript code of the converted HTML page htmlToPdfConverter.TriggeringMode = TriggeringMode.Manual; } byte[] outPdfBuffer = null; if (convertHtmlRadioButton.Checked) { string htmlWithForm = htmlStringTextBox.Text; string baseUrl = baseUrlTextBox.Text; // Convert the HTML string with page-break-inside:avoid styles to a PDF document in a memory buffer outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlWithForm, baseUrl); } else { string url = urlTextBox.Text; // Convert the HTML page with page-break-inside:avoid styles to a PDF document in a memory buffer outPdfBuffer = htmlToPdfConverter.ConvertUrl(url); } // Send the PDF as response to browser // Set response content type Response.AddHeader("Content-Type", "application/pdf"); // Instruct the browser to open the PDF file as an attachment or inline Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Conversion_Triggering_Modes.pdf; size={0}", outPdfBuffer.Length.ToString())); // Write the PDF document buffer to HTTP response Response.BinaryWrite(outPdfBuffer); // End the HTTP response and stop the current page processing Response.End(); }
protected void convertToPdfButton_Click(object sender, EventArgs e) { // Create a HTML to PDF converter object with default settings HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(); // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish htmlToPdfConverter.ConversionDelay = 2; // Html Viewer Options // Set HTML Viewer width in pixels which is the equivalent in converter of the browser window width // This is a preferred width of the browser but the actual HTML content width can be larger in case the HTML page // cannot be entirely displayed in the given viewer width // This property gives the size of the HTML content which can be further scaled to fit the PDF page based on selected options // The HTML content size is in pixels and the PDF page size is in points (1 point = 1/72 inches) // The converter is using a 96 DPI resolution to transform pixels to points with the following formula: Points = Pixels/96 * 72 htmlToPdfConverter.HtmlViewerWidth = int.Parse(htmlViewerWidthTextBox.Text); // Set HTML viewer height in pixels to convert the top part of a HTML page // Leave it not set to convert the entire HTML if (htmlViewerHeightTextBox.Text.Length > 0) { htmlToPdfConverter.HtmlViewerHeight = int.Parse(htmlViewerHeightTextBox.Text); } // Set the HTML content clipping option to force the HTML content width to be exactly HtmlViewerWidth pixels // If this option is false then the actual HTML content width can be larger than HtmlViewerWidth pixels in case the HTML page // cannot be entirely displayed in the given viewer width // By default this option is false and the HTML content is not clipped htmlToPdfConverter.ClipHtmlView = clipContentCheckBox.Checked; // PDF Page Options // Set PDF page size which can be a predefined size like A4 or a custom size in points // Leave it not set to have a default A4 PDF page htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = SelectedPdfPageSize(); // Set PDF page orientation to Portrait or Landscape // Leave it not set to have a default Portrait orientation for PDF page htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = SelectedPdfPageOrientation(); // Set PDF page margins in points or leave them not set to have a PDF page without margins htmlToPdfConverter.PdfDocumentOptions.LeftMargin = float.Parse(leftMarginTextBox.Text); htmlToPdfConverter.PdfDocumentOptions.RightMargin = float.Parse(rightMarginTextBox.Text); htmlToPdfConverter.PdfDocumentOptions.TopMargin = float.Parse(topMarginTextBox.Text); htmlToPdfConverter.PdfDocumentOptions.BottomMargin = float.Parse(bottomMarginTextBox.Text); // HTML Content Destination and Spacing Options // Set HTML content destination in PDF page if (xLocationTextBox.Text.Length > 0) { htmlToPdfConverter.PdfDocumentOptions.X = float.Parse(xLocationTextBox.Text); } if (yLocationTextBox.Text.Length > 0) { htmlToPdfConverter.PdfDocumentOptions.Y = float.Parse(yLocationTextBox.Text); } if (contentWidthTextBox.Text.Length > 0) { htmlToPdfConverter.PdfDocumentOptions.Width = float.Parse(contentWidthTextBox.Text); } if (contentHeightTextBox.Text.Length > 0) { htmlToPdfConverter.PdfDocumentOptions.Height = float.Parse(contentHeightTextBox.Text); } // Set HTML content top and bottom spacing or leave them not set to have no spacing for the HTML content htmlToPdfConverter.PdfDocumentOptions.TopSpacing = float.Parse(topSpacingTextBox.Text); htmlToPdfConverter.PdfDocumentOptions.BottomSpacing = float.Parse(bottomSpacingTextBox.Text); // Scaling Options // Use this option to fit the HTML content width in PDF page width // By default this property is true and the HTML content can be resized to fit the PDF page width htmlToPdfConverter.PdfDocumentOptions.FitWidth = fitWidthCheckBox.Checked; // Use this option to enable the HTML content stretching when its width is smaller than PDF page width // This property has effect only when FitWidth option is true // By default this property is false and the HTML content is not stretched htmlToPdfConverter.PdfDocumentOptions.StretchToFit = stretchCheckBox.Checked; // Use this option to automatically dimension the PDF page to display the HTML content unscaled // This property has effect only when the FitWidth property is false // By default this property is true and the PDF page is automatically dimensioned when FitWidth is false htmlToPdfConverter.PdfDocumentOptions.AutoSizePdfPage = autoSizeCheckBox.Checked; // Use this option to fit the HTML content height in PDF page height // If both FitWidth and FitHeight are true then the HTML content will resized if necessary to fit both width and height // preserving the aspect ratio at the same time // By default this property is false and the HTML content is not resized to fit the PDF page height htmlToPdfConverter.PdfDocumentOptions.FitHeight = fitHeightCheckBox.Checked; // Use this option to render the whole HTML content into a single PDF page // The PDF page size is limited to 14400 points // By default this property is false htmlToPdfConverter.PdfDocumentOptions.SinglePage = singlePageCheckBox.Checked; string url = urlTextBox.Text; // Convert the HTML page to a PDF document using the scaling options byte[] outPdfBuffer = htmlToPdfConverter.ConvertUrl(url); // Send the PDF as response to browser // Set response content type Response.AddHeader("Content-Type", "application/pdf"); // Instruct the browser to open the PDF file as an attachment or inline Response.AddHeader("Content-Disposition", String.Format("attachment; filename=HTML_Content_Scaling.pdf; size={0}", outPdfBuffer.Length.ToString())); // Write the PDF document buffer to HTTP response Response.BinaryWrite(outPdfBuffer); // End the HTTP response and stop the current page processing Response.End(); }
public ActionResult ConvertHtmlToPdf(IFormCollection collection) { // Create a HTML to PDF converter object with default settings HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(); // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish htmlToPdfConverter.ConversionDelay = 2; // Select the HTML elements for which to retrieve location and other information from HTML document htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors = new string[] { collection["htmlElementsSelectorTextBox"] }; Document pdfDocument = null; try { // Convert HTML page to a PDF document object which can be further modified to highlight the selected elements pdfDocument = htmlToPdfConverter.ConvertUrlToPdfDocumentObject(collection["urlTextBox"]); // Highlight the selected elements in PDF with colored rectangles foreach (HtmlElementMapping htmlElementInfo in htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult) { // Get other information about HTML element string htmlElementTagName = htmlElementInfo.HtmlElementTagName; string htmlElementID = htmlElementInfo.HtmlElementId; // Hightlight the HTML element in PDF // A HTML element can span over many PDF pages and therefore the mapping of the HTML element in PDF document consists // in a list of rectangles, one rectangle for each PDF page where this element was rendered foreach (HtmlElementPdfRectangle htmlElementLocationInPdf in htmlElementInfo.PdfRectangles) { // Get the HTML element location in PDF page PdfPage htmlElementPdfPage = htmlElementLocationInPdf.PdfPage; RectangleF htmlElementRectangleInPdfPage = htmlElementLocationInPdf.Rectangle; // Highlight the HTML element element with a colored rectangle in PDF RectangleElement highlightRectangle = new RectangleElement(htmlElementRectangleInPdfPage.X, htmlElementRectangleInPdfPage.Y, htmlElementRectangleInPdfPage.Width, htmlElementRectangleInPdfPage.Height); if (htmlElementTagName.ToLower() == "h1") { highlightRectangle.ForeColor = Color.Blue; } else if (htmlElementTagName.ToLower() == "h2") { highlightRectangle.ForeColor = Color.Green; } else if (htmlElementTagName.ToLower() == "h3") { highlightRectangle.ForeColor = Color.Red; } else if (htmlElementTagName.ToLower() == "h4") { highlightRectangle.ForeColor = Color.Yellow; } else if (htmlElementTagName.ToLower() == "h5") { highlightRectangle.ForeColor = Color.Indigo; } else if (htmlElementTagName.ToLower() == "h6") { highlightRectangle.ForeColor = Color.Orange; } else { highlightRectangle.ForeColor = Color.Navy; } highlightRectangle.LineStyle.LineDashStyle = LineDashStyle.Solid; htmlElementPdfPage.AddElement(highlightRectangle); } } // Save the PDF document in a memory buffer byte[] outPdfBuffer = pdfDocument.Save(); // Send the PDF file to browser FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf"); fileResult.FileDownloadName = "Select_in_API_HTML_Elements_to_Retrieve.pdf"; return(fileResult); } finally { // Close the PDF document if (pdfDocument != null) { pdfDocument.Close(); } } }
protected void convertToPdfButton_Click(object sender, EventArgs e) { // Create a HTML to PDF converter object with default settings htmlToPdfConverter = new HtmlToPdfConverter(); // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish htmlToPdfConverter.ConversionDelay = 2; // Enable header in the generated PDF document htmlToPdfConverter.PdfDocumentOptions.ShowHeader = true; string headerHtmlUrl = Server.MapPath("~/DemoAppFiles/Input/HTML_Files/Header_HTML.html"); Document documentObject = null; try { if (autoResizeHeaderRadioButton.Checked) { // Create a HTML element to be added in header HtmlToPdfElement headerHtml = new HtmlToPdfElement(headerHtmlUrl); // Install a handler where to set the automatically calculated header height headerHtml.NavigationCompletedEvent += new NavigationCompletedDelegate(headerHtml_NavigationCompletedEvent); // Add the HTML element to header // When the element is rendered in header by converter, the headerHtml_NavigationCompletedEvent handler // will be invoked and the header height will be automatically calculated htmlToPdfConverter.PdfHeaderOptions.AddElement(headerHtml); // Call the converter to produce a Document object documentObject = htmlToPdfConverter.ConvertUrlToPdfDocumentObject(urlTextBox.Text); // Uninstall the handler headerHtml.NavigationCompletedEvent -= new NavigationCompletedDelegate(headerHtml_NavigationCompletedEvent); // Draw a line at the header bottom if (drawHeaderLine) { float headerWidth = documentObject.Header.Width; float headerHeight = documentObject.Header.Height; // Create a line element for the bottom of the header LineElement headerLine = new LineElement(0, headerHeight - 1, headerWidth, headerHeight - 1); // Set line color headerLine.ForeColor = Color.Gray; // Add line element to the bottom of the header documentObject.Header.AddElement(headerLine); } // Save the PDF document in a memory buffer byte[] outPdfBuffer = documentObject.Save(); // Send the PDF as response to browser // Set response content type Response.AddHeader("Content-Type", "application/pdf"); // Instruct the browser to open the PDF file as an attachment or inline Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Auto_Resize_Header_Footer.pdf; size={0}", outPdfBuffer.Length.ToString())); // Write the PDF document buffer to HTTP response Response.BinaryWrite(outPdfBuffer); // End the HTTP response and stop the current page processing Response.End(); } else { // Create a HTML to PDF element to be added in header HtmlToPdfElement headerHtml = new HtmlToPdfElement(headerHtmlUrl); // Set a fixed header height in points htmlToPdfConverter.PdfHeaderOptions.HeaderHeight = float.Parse(headerHeightTextBox.Text); // Set the HTML element to fit the container height headerHtml.FitHeight = true; // Add HTML element to fit the fixed header height htmlToPdfConverter.PdfHeaderOptions.AddElement(headerHtml); // Draw a line at the header bottom if (drawHeaderLine) { // Calculate the header width based on PDF page size and margins float headerWidth = htmlToPdfConverter.PdfDocumentOptions.PdfPageSize.Width - htmlToPdfConverter.PdfDocumentOptions.LeftMargin - htmlToPdfConverter.PdfDocumentOptions.RightMargin; // Calculate header height float headerHeight = htmlToPdfConverter.PdfHeaderOptions.HeaderHeight; // Create a line element for the bottom of the header LineElement headerLine = new LineElement(0, headerHeight - 1, headerWidth, headerHeight - 1); // Set line color headerLine.ForeColor = Color.Gray; // Add line element to the bottom of the header htmlToPdfConverter.PdfHeaderOptions.AddElement(headerLine); } // Convert the HTML page to a PDF document in a memory buffer byte[] outPdfBuffer = htmlToPdfConverter.ConvertUrl(urlTextBox.Text); // Send the PDF as response to browser // Set response content type Response.AddHeader("Content-Type", "application/pdf"); // Instruct the browser to open the PDF file as an attachment or inline Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Auto_Resize_Header_Footer.pdf; size={0}", outPdfBuffer.Length.ToString())); // Write the PDF document buffer to HTTP response Response.BinaryWrite(outPdfBuffer); // End the HTTP response and stop the current page processing Response.End(); } } finally { // Close the PDF document if (documentObject != null) { documentObject.Close(); } } }
public ActionResult ConvertHtmlToPdf(IFormCollection collection) { // Create a HTML to PDF converter object with default settings HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(); // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish htmlToPdfConverter.ConversionDelay = 2; // Set the encryption algorithm and the encryption key size if they are not the default ones if (collection["EncryptionKey"] != "bit128RadioButton" || collection["EncryptionType"] != "rc4RadioButton") { // set the encryption algorithm htmlToPdfConverter.PdfSecurityOptions.EncryptionAlgorithm = collection["EncryptionType"] == "rc4RadioButton" ? EncryptionAlgorithm.RC4 : EncryptionAlgorithm.AES; // set the encryption key size if (collection["EncryptionKey"] == "bit40RadioButton") { htmlToPdfConverter.PdfSecurityOptions.KeySize = EncryptionKeySize.EncryptKey40Bit; } else if (collection["EncryptionKey"] == "bit128RadioButton") { htmlToPdfConverter.PdfSecurityOptions.KeySize = EncryptionKeySize.EncryptKey128Bit; } else if (collection["EncryptionKey"] == "bit256RadioButton") { htmlToPdfConverter.PdfSecurityOptions.KeySize = EncryptionKeySize.EncryptKey256Bit; } } // Set user and owner passwords if (collection["userPasswordTextBox"][0].Length > 0) { htmlToPdfConverter.PdfSecurityOptions.UserPassword = collection["userPasswordTextBox"]; } if (collection["ownerPasswordTextBox"][0].Length > 0) { htmlToPdfConverter.PdfSecurityOptions.OwnerPassword = collection["ownerPasswordTextBox"]; } // Set PDF document permissions htmlToPdfConverter.PdfSecurityOptions.CanPrint = collection["printEnabledCheckBox"].Count > 0; htmlToPdfConverter.PdfSecurityOptions.CanPrintHighResolution = collection["highResolutionPrintEnabledCheckBox"].Count > 0; htmlToPdfConverter.PdfSecurityOptions.CanCopyContent = collection["copyContentEnabledCheckBox"].Count > 0; htmlToPdfConverter.PdfSecurityOptions.CanCopyAccessibilityContent = collection["copyAccessibilityContentEnabledCheckBox"].Count > 0; htmlToPdfConverter.PdfSecurityOptions.CanEditContent = collection["editContentEnabledCheckBox"].Count > 0; htmlToPdfConverter.PdfSecurityOptions.CanEditAnnotations = collection["editAnnotationsEnabledCheckBox"].Count > 0; htmlToPdfConverter.PdfSecurityOptions.CanFillFormFields = collection["fillFormFieldsEnabledCheckBox"].Count > 0; if ((PermissionsChanged(htmlToPdfConverter) || htmlToPdfConverter.PdfSecurityOptions.UserPassword.Length > 0) && htmlToPdfConverter.PdfSecurityOptions.OwnerPassword.Length == 0) { // A user password is set but the owner password is not set or the permissions are not the default ones // Set a default owner password htmlToPdfConverter.PdfSecurityOptions.OwnerPassword = "******"; } // Convert the HTML page to a PDF document in a memory buffer byte[] outPdfBuffer = htmlToPdfConverter.ConvertUrl(collection["urlTextBox"]); // Send the PDF file to browser FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf"); fileResult.FileDownloadName = "Set_Permissions_Password.pdf"; return(fileResult); }
protected void convertToPdfButton_Click(object sender, EventArgs e) { // Create a HTML to PDF converter object with default settings HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(); // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set HTML Viewer width in pixels which is the equivalent in converter of the browser window width htmlToPdfConverter.HtmlViewerWidth = int.Parse(htmlViewerWidthTextBox.Text); // Set HTML viewer height in pixels to convert the top part of a HTML page // Leave it not set to convert the entire HTML if (htmlViewerHeightTextBox.Text.Length > 0) { htmlToPdfConverter.HtmlViewerHeight = int.Parse(htmlViewerHeightTextBox.Text); } // Set PDF page size which can be a predefined size like A4 or a custom size in points // Leave it not set to have a default A4 PDF page htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = SelectedPdfPageSize(); // Set PDF page orientation to Portrait or Landscape // Leave it not set to have a default Portrait orientation for PDF page htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = SelectedPdfPageOrientation(); // Set the maximum time in seconds to wait for HTML page to be loaded // Leave it not set for a default 60 seconds maximum wait time htmlToPdfConverter.NavigationTimeout = int.Parse(navigationTimeoutTextBox.Text); // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish if (conversionDelayTextBox.Text.Length > 0) { htmlToPdfConverter.ConversionDelay = int.Parse(conversionDelayTextBox.Text); } // The buffer to receive the generated PDF document byte[] outPdfBuffer = null; if (convertUrlRadioButton.Checked) { string url = urlTextBox.Text; // Convert the HTML page given by an URL to a PDF document in a memory buffer outPdfBuffer = htmlToPdfConverter.ConvertUrl(url); } else { string htmlString = htmlStringTextBox.Text; string baseUrl = baseUrlTextBox.Text; // Convert a HTML string with a base URL to a PDF document in a memory buffer outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlString, baseUrl); } // Send the PDF as response to browser // Set response content type Response.AddHeader("Content-Type", "application/pdf"); // Instruct the browser to open the PDF file as an attachment or inline Response.AddHeader("Content-Disposition", String.Format("{0}; filename=Getting_Started.pdf; size={1}", openInlineCheckBox.Checked ? "inline" : "attachment", outPdfBuffer.Length.ToString())); // Write the PDF document buffer to HTTP response Response.BinaryWrite(outPdfBuffer); // End the HTTP response and stop the current page processing Response.End(); }
public ActionResult GeneratePdf(string htmlContent, string htmlUrl) { string[] htmlFiles; try { htmlFiles = Directory.GetFiles(htmlUrl); } catch (Exception e) { throw e; } HtmlAgilityPack.HtmlDocument doc = new HtmlAgilityPack.HtmlDocument(); foreach (var htmlDoc in htmlFiles) { doc.Load(htmlDoc); var x = doc.DocumentNode.SelectSingleNode("//div[@class='pageHeader']"); if (!object.Equals(x, null)) { x.Remove(); } x = doc.DocumentNode.SelectSingleNode("//div[@class='leftNav']"); if (!object.Equals(x, null)) { x.Remove(); } x = doc.DocumentNode.SelectSingleNode("//div[@class='topicContent']"); if (!object.Equals(x, null)) { x.SetAttributeValue("Style", "margin-left: 0px; margin-top: 100px;"); } MemoryStream output = new System.IO.MemoryStream(); doc.Save(output); System.IO.File.WriteAllBytes(htmlDoc, output.ToArray()); } var htmlToPdf = new HtmlToPdfConverter(); htmlToPdf.Orientation = PageOrientation.Landscape; htmlToPdf.PageHeaderHtml = "<img width='182' height='75' src='https://www.avanade.com/~/media/logo/avanade-logo.svg' align='right' hspace='12' v:shapes='Picture_x0020_2'>"; htmlToPdf.PageFooterHtml = "<span style='font-size:8.0pt;font-family:"Segoe UI",sans-serif;color:#70AD47;mso-themecolor:accent6;mso-font-kerning:12.0pt'> </span><span style='font-size:" + "8.0pt; font - family:" Segoe UI",sans - serif; color: black; mso - themecolor:text1; mso - font - kerning:12.0pt'><Confidential> See Avanade’s </span><a href='https://at.avanade.com/organizations/Policies/Policies2/Forms/Document%20Set/docsethomepage.aspx?ID=670&FolderCTID=0x0120D52000634FE8B87F4B4141A21BFCB3CDC3E3D6&List=caf52708-714a-4e5f-ba50-5017dacf9744&RootFolder=/organizations/Policies/Policies2/Data%20Management'><span style='font-size:8.0pt;font-family:"Segoe UI",sans-serif;color:#FF5800;mso-font-kerning:12.0pt'>Data Classification and Protection Standard</span></a><span class='MsoHyperlink'><span style='font-size:8.0pt;font-family:"Segoe UI",sans-serif;color:#70AD47;mso-themecolor:accent6;mso-font-kerning:12.0pt'><o:p></o:p></span></span></p><p class='MsoNormal'><span style='font-size:8.0pt;font-family:"Segoe UI",sans-serif'>©2017 Avanade Inc. All Rights Reserved<o:p></o:p></span>"; var pdfContentType = "application/pdf"; string pdfName = Path.GetTempPath() + "/Document.pdf"; if (!String.IsNullOrEmpty(htmlUrl)) { htmlToPdf.GeneratePdfFromFiles(htmlFiles, null, pdfName); return(File(pdfName, pdfContentType)); } else { return(File(htmlToPdf.GeneratePdf(htmlContent, null), pdfContentType)); } }
public ActionResult ConvertHtmlToPdf(IFormCollection collection) { // Create a HTML to PDF converter object with default settings HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(); // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set HTML Viewer width in pixels which is the equivalent in converter of the browser window width htmlToPdfConverter.HtmlViewerWidth = int.Parse(collection["htmlViewerWidthTextBox"]); // Set HTML viewer height in pixels to convert the top part of a HTML page // Leave it not set to convert the entire HTML if (collection["htmlViewerHeightTextBox"][0].Length > 0) { htmlToPdfConverter.HtmlViewerHeight = int.Parse(collection["htmlViewerHeightTextBox"]); } // Set PDF page size which can be a predefined size like A4 or a custom size in points // Leave it not set to have a default A4 PDF page htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = SelectedPdfPageSize(collection["pdfPageSizeDropDownList"]); // Set PDF page orientation to Portrait or Landscape // Leave it not set to have a default Portrait orientation for PDF page htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = SelectedPdfPageOrientation(collection["pdfPageOrientationDropDownList"]); // Set the maximum time in seconds to wait for HTML page to be loaded // Leave it not set for a default 60 seconds maximum wait time htmlToPdfConverter.NavigationTimeout = int.Parse(collection["navigationTimeoutTextBox"]); // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish if (collection["conversionDelayTextBox"][0].Length > 0) { htmlToPdfConverter.ConversionDelay = int.Parse(collection["conversionDelayTextBox"]); } // The buffer to receive the generated PDF document byte[] outPdfBuffer = null; if (collection["HtmlPageSource"] == "convertUrlRadioButton") { string url = collection["urlTextBox"]; // Convert the HTML page given by an URL to a PDF document in a memory buffer outPdfBuffer = htmlToPdfConverter.ConvertUrl(url); } else { string htmlString = collection["htmlStringTextBox"]; string baseUrl = collection["baseUrlTextBox"]; // Convert a HTML string with a base URL to a PDF document in a memory buffer outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlString, baseUrl); } // Send the PDF file to browser FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf"); if (collection["openInlineCheckBox"].Count == 0) { // send as attachment fileResult.FileDownloadName = "Getting_Started.pdf"; } return(fileResult); }
protected void convertToPdfButton_Click(object sender, EventArgs e) { // Get the server IP and port String serverIP = textBoxServerIP.Text; uint serverPort = uint.Parse(textBoxServerPort.Text); // Create a HTML to PDF converter object with default settings HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(serverIP, serverPort); // Set optional service password if (textBoxServicePassword.Text.Length > 0) { htmlToPdfConverter.ServicePassword = textBoxServicePassword.Text; } // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish htmlToPdfConverter.ConversionDelay = 2; // Optionally set the table of contents title htmlToPdfConverter.TableOfContentsOptions.Title = "Table of Contents"; // Optionally set the title style using CSS sttributes htmlToPdfConverter.TableOfContentsOptions.TitleStyle = "color:navy; font-family:'Times New Roman'; font-size:28px; font-weight:normal"; // Optionally set the style of level 1 items in table of contents string level1TextStyle = "color:navy; font-family:'Times New Roman'; font-size:20px; font-weight:normal; font-style:normal; background-color:#F0F0F0"; htmlToPdfConverter.TableOfContentsOptions.SetItemStyle(1, level1TextStyle); // Optionally set the page numbers style of level 1 items in table of contents string level1PageNumberStyle = "color:navy; padding-right:3px; background-color:#F0F0F0; font-size:14px; font-weight:bold"; htmlToPdfConverter.TableOfContentsOptions.SetPageNumberStyle(1, level1PageNumberStyle); byte[] outPdfBuffer = null; if (convertHtmlRadioButton.Checked) { string htmlWithBookmarkAttributes = htmlStringTextBox.Text; string baseUrl = baseUrlTextBox.Text; // Convert a HTML string with table of contents to a PDF document in a memory buffer outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlWithBookmarkAttributes, baseUrl); } else { string url = urlTextBox.Text; // Convert a HTML page with table of contents to a PDF document in a memory buffer outPdfBuffer = htmlToPdfConverter.ConvertUrl(url); } // Send the PDF as response to browser // Set response content type Response.AddHeader("Content-Type", "application/pdf"); // Instruct the browser to open the PDF file as an attachment or inline Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Define_in_HTML_Table_of_Contents.pdf; size={0}", outPdfBuffer.Length.ToString())); // Write the PDF document buffer to HTTP response Response.BinaryWrite(outPdfBuffer); // End the HTTP response and stop the current page processing Response.End(); }
public static HtmlToPdfConverter GetInitializedHtmlConverter(string html_string, out string html_body) { HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(); htmlToPdfConverter.PdfDocumentOptions.Width = 750; htmlToPdfConverter.HtmlViewerWidth = 650; htmlToPdfConverter.PdfDocumentOptions.LeftMargin = 50; htmlToPdfConverter.PdfDocumentOptions.RightMargin = 50; htmlToPdfConverter.PdfDocumentOptions.TopMargin = 25; htmlToPdfConverter.PdfDocumentOptions.BottomMargin = 10; htmlToPdfConverter.PdfDocumentOptions.AvoidImageBreak = true; htmlToPdfConverter.PdfDocumentOptions.AvoidTextBreak = true; htmlToPdfConverter.PdfDocumentOptions.JpegCompressionLevel = 0; // Install a handler where to change the header and footer in first page htmlToPdfConverter.PrepareRenderPdfPageEvent += new PrepareRenderPdfPageDelegate(htmlToPdfConverter_PrepareRenderPdfPageEvent); html_body = ""; string header = ""; string footer = ""; int header_height = 0; int footer_height = 0; DocumentTemplate.GetPageParts(html_string, out header, out footer, out html_body, out header_height, out footer_height); if (!string.IsNullOrEmpty(header)) { htmlToPdfConverter.PdfDocumentOptions.ShowHeader = true; htmlToPdfConverter.PdfHeaderOptions.HeaderHeight = header_height; HtmlToPdfElement headerElem = new HtmlToPdfElement(0, 0, 0, header, "", 680); headerElem.FitHeight = true; htmlToPdfConverter.PdfHeaderOptions.AddElement(headerElem); } if (!string.IsNullOrEmpty(footer)) { htmlToPdfConverter.PdfDocumentOptions.ShowFooter = true; HtmlToPdfElement footerElem = new HtmlToPdfElement(footer, ""); if (footer_height > 0) htmlToPdfConverter.PdfFooterOptions.FooterHeight = footer_height; else footerElem.FitHeight = true; htmlToPdfConverter.PdfFooterOptions.AddElement(footerElem); } htmlToPdfConverter.LicenseKey = "sjwvPS4uPSskPSgzLT0uLDMsLzMkJCQk"; htmlToPdfConverter.PdfDocumentOptions.AvoidImageBreak = true; return htmlToPdfConverter; }
public IActionResult CreatePDF(int id) { //Variables string invoiceNumber = ""; string logo = Path.Combine(_env.WebRootPath, "images/" + _settings.Logo); //Instances Invoice invoice = null; Debtor debtor = null; Company company = null; List <InvoiceItem> invoiceItems = null; List <Product> productList = new List <Product>(); try { invoice = _context.Invoices.SingleOrDefault(s => s.InvoiceNumber == id); debtor = _context.Debtors.SingleOrDefault(s => s.DebtorID == invoice.DebtorID); invoiceItems = _context.InvoiceItems.Where(s => s.InvoiceNumber == invoice.InvoiceNumber).ToList(); if (debtor == null) { int cid = (int)invoice.CompanyID; company = _context.Companies.SingleOrDefault(s => s.CompanyID == cid); } } catch (Exception ex) { Debug.WriteLine(ex); } foreach (var item in invoiceItems) { Product product = _context.Products.Single(s => s.ProductID == item.ProductID); productList.Add(product); } if (_settings.Prefix != "") { invoiceNumber = _settings.Prefix + "-" + invoice.InvoiceNumber.ToString(); } else { invoiceNumber = invoice.InvoiceNumber.ToString(); } //CSS string var cssString = @"<style> .invoice-box { max-width: 2480px; max-height: 3495px: width: 100%; height: 90%; margin: auto 0; padding: 30px 7px; font-size: 15px; line-height: 24px; font-family: 'Helvetica Neue', 'Helvetica', Helvetica, Arial, sans-serif; color: #555; letter-spacing: 0px; } .invoice-box table { width: 100%; line-height: inherit; text-align: left; } .invoice-box table td { padding: 5px 0px; vertical-align: top; } .invoice-box table tr.top table td { padding-bottom: 50px; } .invoice-box table .top td .title { font-size: 32px; line-height: 32px; padding-left: 65px !important; color: #333; float: left; width: 80%; text-align: left; } .invoice-box table .top td .logo { padding-left: 0px !important; float: left; max-width: 65%; height: auto; text-align: left; } .invoice-box table .top .company { float: right; font-size: 13.5px; text-align: left !important; width: 30%; align: right !important; margin-right: 0; padding-right: 10px; margin-left: 10px; } .invoice-box table .top .company hr{ margin-left: auto; margin-right: auto; width: 100%; height: 2px; margin-top: 2px; margin-bottom: 0; padding-bottom: 1px; } .invoice-box .debtor-table{ margin-left: 55px !important; margin-bottom: 45px !important; } .invoice-box .debtor-table .debtor-info{ border-collapse: collapse; border-spacing; 0; padding: 0 0 0 0; margin: 0 0 0 15px; } .invoice-box .debtor-table .debtor-info tr{ padding: 0 0 0 0; margin: 0 0 0 0; } .invoice-box .debtor-table .debtor-name, .invoice-box .debtor-table .debtor-address, .invoice-box .debtor-table .debtor-city{ font-size: 16px; text-align: left !important; padding-bottom: 0px; line-height: normal; } .invoice-box .invoice-info{ border-collapse: collapse; border-spacing; 0; padding: 0 0 0 0; margin: 8px 0 65px 55px !important; width: 30%; } .invoice-box .invoice-info tr{ margin: 0 0 0 0 !important; padding: 0 0 0 0; line-height: 64%; font-size: 16px; border-collapse: collapse; border-spacing; 0; } .invoice-box .invoice-info tr td:nth-child(1){ width: 40%; } .invoice-box .invoice-info tr td:nth-child(2){ width: 60% padding-left: 2px; text-align: left; align: left; } .invoice-box .item-table tr.heading td { background: #eee; border-bottom: 1px solid #ddd; font-weight: bold; font-size: 15px; } .invoice-box .item-table tr.details td { padding-bottom: 20px; } .invoice-box .item-table{ margin-bottom: 25px !important; } .invoice-box .item-table tr.item td { border-bottom: 1px solid #eee; font-size: 14px; } .invoice-box .item-table tr.item.last td { border-bottom: none; } .invoice-box .item-table tr td:nth-child(1){ border-top: 2px solid #eee; width: 26%; padding-left: 4px; } .invoice-box .item-table tr td:nth-child(2){ width: 34%; } .invoice-box .item-table tr td:nth-child(4), .invoice-box .item-table tr td:nth-child(5), .invoice-box .item-table tr td:nth-child(6){ text-align: center; } .invoice-box .item-table tr td:nth-child(3){ width: 12%; text-align: center; } .invoice-box .item-table tr td:nth-child(4), .invoice-box .item-table tr td:nth-child(5){ width: 8%; } .invoice-box .item-table tr td:nth-child(6){ width: 12% } .invoice-box .total-table{ border-collapse: collapse; border-spacing; 0; width: 18%; float: right; margin: 5px 35px 0 0 !important; padding: 0 0 0 0 !important; } .invoice-box .total-table .total{ border-top: 1px solid #888; } .invoice-box .total-table tr td:nth-child(1){ font-weight: 600; text-align: right; font-size: 15px; padding-bottom: 1px; width: 40%; } .invoice-box .total-table tr td:nth-child(2){ font-weight: 800; text-align: left; font-size: 15px; padding-bottom: 1px; padding-left: 6px; width: 60%; } .invoice-box .disclaimer-table{ width: 100%; border-top: 2px solid #DDD; margin: 0 0 0 0 !important; padding: 0 0 0 0 !important; position: fixed !important; bottom: 4%; left: 0%; } .invoice-box .disclaimer-table .message .message-text{ font-size: 16px; text-align: center; padding: 5px 25px !important; } @media only screen and (max-width: 600px) { .invoice-box table tr.top table td { width: 100%; display: block; text-align: center; } .invoice-box table tr.information table td { width: 100%; display: block; text-align: center; } } </style>"; //Company string string companyString = @"<div class=invoice-box> <table cellpadding=0 cellspacing=0> <tr class=top> <td colspan=2> <table> <tr> <td class=title>"; if (_settings.UseLogoInPDF == true) { companyString += "<img class=logo src=" + logo + " />"; } else { companyString += "<h2>" + _settings.CompanyName + "</h2>"; } companyString += "</td>" + "<td class=company>" + "<b>" + _settings.CompanyName + "</b>" + "<hr />" + _settings.Address + "<br />" + _settings.PostalCode + " " + _settings.City + "<br />" + _settings.Country + "<hr />" + "<b>Tel: </b>" + _settings.Phone + "<br />" + "<b>Web: </b>" + _settings.Website + "<hr />" + "<b>Reg No: </b>" + _settings.RegNumber + "<br />" + "<b>VAT: </b>" + _settings.FinancialNumber + "</td>" + "</tr> " + "</table> " + "</td>" + "</tr>" + "</table>"; string debtorString = ""; //Debtor string if (debtor != null) { debtorString = @"<table class=debtor-table cellpadding=0 cellspacing=0>" + "<tr>" + "<td class=debtor-name>" + debtor.FirstName + " " + debtor.LastName + "</td>" + "</tr>" + "<tr>" + "<td class=debtor-address>" + debtor.Address + "</td>" + "</tr>" + "<tr>" + "<td class=debtor-city>" + debtor.PostalCode + " " + debtor.City + "</td>" + "</tr>" + "</table>"; } else if (company != null) { debtorString = @"<table class=debtor-table cellpadding=0 cellspacing=0>" + "<tr>" + "<td class=debtor-name>" + company.CompanyName + "</td>" + "</tr>" + "<tr>" + "<td class=debtor-address>" + company.Address + "</td>" + "</tr>" + "<tr>" + "<td class=debtor-city>" + company.PostalCode + " " + company.City + "</td>" + "</tr>" + "</table>"; } //Spacer string string spacerString = @"<br />"; //Invoice info string invoiceString = @"<table class=invoice-info cellpadding=0 cellspacing=0>" + "<tr>" + "<td><b>Date: </b></td>" + "<td>" + invoice.CreatedOn.ToString("dd-MM-yyyy") + "</td>" + "</tr>" + "<tr>" + "<td><b>Invoice No: </b></td>" + "<td>" + invoiceNumber + "</td>" + "</tr>" + "</table>"; //Product string string productString = @"<table class=item-table cellpadding=0 cellspacing=0>" + "<tr class=heading> " + "<td>Product</td>" + "<td>Description</td>" + "<td>Price</td>" + "<td>Qnt</td>" + "<td>VAT</td>" + "<td>Total</td>" + "</tr>"; //Table string string tableString = ""; decimal totalBeforeDiscount = 0; decimal totalAmount = invoice.Total; decimal subTotalAmount = 0; decimal vatTotalAmount = 0; decimal discount = 0; int discountPercentage = invoice.Discount; for (int i = 0; i < invoiceItems.Count; i++) { InvoiceItem item = invoiceItems[i]; Product product = productList.Single(s => s.ProductID == item.ProductID); int vatPercentage = 100 + product.VAT; decimal total = (decimal)(product.Price * item.Amount); decimal subTotal = (decimal)(product.Price * 100) / vatPercentage; totalBeforeDiscount += total; subTotalAmount += subTotal; tableString += @"<tr class=item>" + "<td>" + product.Name + "</td>" + "<td>" + product.Description + "</td>" + "<td>€ " + String.Format("{0:N2}", product.Price) + "</td>" + "<td>" + item.Amount + "</td>" + "<td>" + String.Format("{0}%", product.VAT) + "</td>" + "<td>€ " + String.Format("{0:N2}", total) + "</td>" + "</tr>"; } vatTotalAmount = totalAmount - subTotalAmount; discount = (totalBeforeDiscount * discountPercentage) / 100; Debug.WriteLine("Discount Percentage: " + discountPercentage + "%"); Debug.WriteLine("Discount: " + discount); tableString += "</table>"; //Total string string totalString = @"<table class=total-table cellspacing=0 cellpadding=0>" + "<tr class=vat>" + "<td>VAT:</td>" + "<td>€ " + String.Format("{0:N2}", vatTotalAmount) + "</td>" + "</tr>" + "<tr class=subtotal>" + "<td>Subtotal:</td>" + "<td>€ " + String.Format("{0:N2}", subTotalAmount) + "</td>" + "</tr>" + "<tr class=discount>" + "<td>Discount:</td>" + "<td>€ " + String.Format("{0:N2}", discount) + "</td>" + "</tr>" + "<tr class=total>" + "<td>Total:</td>" + "<td>€ " + String.Format("{0:N2}", totalAmount) + "</td>" + "</tr>" + "</table>"; //Disclaimer string string disclaimerString = @"<table class=disclaimer-table cellspacing=0 cellpadding=0>" + "<tr class=message>" + "<td><p class=message-text> We kindly request you to pay the amount of <b>" + String.Format("€{0:N2}", totalAmount) + "</b> described above before <b>" + invoice.ExpirationDate.ToString("dd-MM-yyyy") + "</b> on our bank account <b>" + _settings.BankAccountNumber + "</b> in the name of <b>" + _settings.CompanyName + "</b>, indicating the invoice number <b>" + invoiceNumber + "</b>. For questions, please contact." + "</p></td>" + "</tr>" + "</table>" + "</div>"; //Full HTML string string htmlContent = cssString + companyString + debtorString + spacerString + invoiceString + productString + tableString + totalString + disclaimerString; var wkhtmltopdf = new FileInfo(@"wkhtmltopdf\bin\wkhtmltopdf.exe"); var converter = new HtmlToPdfConverter(wkhtmltopdf); var pdfBytes = converter.ConvertToPdf(htmlContent); FileResult fileResult = new FileContentResult(pdfBytes, "application/pdf"); fileResult.FileDownloadName = "invoice-" + id + ".pdf"; return(fileResult); }
/// <summary> /// Converts html into PDF using nReco dll and wkhtmltopdf.exe. /// </summary> private byte[] ConvertHtmlToPDF() { HtmlToPdfConverter nRecohtmltoPdfObj = new HtmlToPdfConverter(); nRecohtmltoPdfObj.Orientation = PageOrientation.Portrait; nRecohtmltoPdfObj.PageFooterHtml = CreatePDFFooter(); nRecohtmltoPdfObj.CustomWkHtmlArgs = "--margin-top 35 --header-spacing 0 --margin-left 0 --margin-right 0"; return nRecohtmltoPdfObj.GeneratePdf(CreatePDFScript() + ShowHtml() + "</body></html>"); }
private PdfDocument ConvertWithWebKitRendering() { //Initialize HTML to PDF converter with WebKit settings HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.WebKit); WebKitConverterSettings converterSettings = new WebKitConverterSettings(); //Set page margins converterSettings.Margin = new PdfMargins() { All = float.Parse(pagemargin) }; //Set page orientation if (rdbtnOrientation == "Portrait") { converterSettings.Orientation = PdfPageOrientation.Portrait; } else { converterSettings.Orientation = PdfPageOrientation.Landscape; } //Set rotation converterSettings.PageRotateAngle = (PdfPageRotateAngle)Enum.Parse(typeof(PdfPageRotateAngle), rotate); //Enable Javascript converterSettings.EnableJavaScript = chkEnableJavaScript == "on" ? true : false; //Enable Hyperlink converterSettings.EnableHyperLink = chkEnableHyperlink == "on" ? true : false; //Enable Form converterSettings.EnableForm = chkEnableForm == "on" ? true : false; //Enabel Toc converterSettings.EnableToc = chkEnableToc == "on" ? true : false; //Enable Bookmark converterSettings.EnableBookmarks = chkEnableBookmark == "on" ? true : false; //Set WebKit viewport size int viewportWidth = 1024; if (int.TryParse(ViewportWidth, out viewportWidth)) { } int viewportHeight = 0; if (int.TryParse(ViewportHeight, out viewportHeight)) { } converterSettings.WebKitViewPort = new Size(viewportWidth, viewportHeight); //Set WebKitPath string WebKitBinaryPath = ResolveApplicationImagePath("QtBinaries"); converterSettings.WebKitPath = WebKitBinaryPath; //Set additional delay if (int.TryParse(jsAdditionalDelay, out int additionalDelay)) { converterSettings.AdditionalDelay = additionalDelay * 1000; } //Adding Header if (showHeader == "on") { converterSettings.PdfHeader = this.AddHeader(converterSettings.PdfPageSize.Width, "Syncfusion Essential PDF", " "); } //Adding Footer if (showFooter == "on") { converterSettings.PdfFooter = this.AddFooter(converterSettings.PdfPageSize.Height, "@Copyright 2016"); } //Assign WebKit settings to HTML converter htmlConverter.ConverterSettings = converterSettings; //Convert url to pdf Pdfdoc = htmlConverter.Convert(sourceUrl); return(Pdfdoc); }
static void Main(string[] args) { try { // Parse MessageContents using MsgReader Library // MsgReader library can be obtained from: https://github.com/Sicos1977/MSGReader using (var msg = new MsgReader.Outlook.Storage.Message("HtmlSampleEmail.msg")) { // Get Sender information var from = msg.GetEmailSender(false, false); // Message sent datetime var sentOn = msg.SentOn; // Recipient To information var recipientsTo = msg.GetEmailRecipients(MsgReader.Outlook.RecipientType.To, false, false); // Recipient CC information var recipientsCc = msg.GetEmailRecipients(MsgReader.Outlook.RecipientType.Cc, false, false); // Message subject var subject = msg.Subject; // Get Message Body var msgBody = msg.BodyHtml; // Prepare PDF docuemnt using (Document outputDocument = new Document()) { // Add registration keys outputDocument.RegistrationName = "demo"; outputDocument.RegistrationKey = "demo"; // Add page Page page = new Page(PaperFormat.A4); outputDocument.Pages.Add(page); // Add sample content Font font = new Font(StandardFonts.Times, 12); Brush brush = new SolidBrush(); // Add Email contents int topMargin = 20; page.Canvas.DrawString($"File Name: {msg.FileName}", font, brush, 20, (topMargin += 20)); page.Canvas.DrawString($"From: {from}", font, brush, 20, (topMargin += 20)); page.Canvas.DrawString($"Sent On: {(sentOn.HasValue ? sentOn.Value.ToString("MM/dd/yyyy HH:mm") : "")}", font, brush, 20, (topMargin += 20)); page.Canvas.DrawString($"To: {recipientsTo}", font, brush, 20, (topMargin += 20)); if (!string.IsNullOrEmpty(recipientsCc)) { page.Canvas.DrawString($"CC: {recipientsCc}", font, brush, 20, (topMargin += 20)); } page.Canvas.DrawString($"Subject: {subject}", font, brush, 20, (topMargin += 20)); page.Canvas.DrawString("Message body in next page.", font, brush, 20, (topMargin += 20)); // Convert Html body to PDF in order to retain all formatting. using (HtmlToPdfConverter converter = new HtmlToPdfConverter()) { converter.PageSize = PaperKind.A4; converter.Orientation = Bytescout.PDF.Converters.PaperOrientation.Portrait; // Convert input HTML to stream byte[] byteArrayBody = Encoding.UTF8.GetBytes(msgBody); MemoryStream inputStream = new MemoryStream(byteArrayBody); // Create output stream to store generated PDF file using (var outputStream = new MemoryStream()) { // Convert HTML to PDF converter.ConvertHtmlToPdf(inputStream, outputStream); // Create new document from generated output stream Document docContent = new Document(outputStream); // Append all pages to main PDF foreach (Page item in docContent.Pages) { outputDocument.Pages.Add(item); } // Save output file outputDocument.Save("result.pdf"); } } // Open result document in default associated application (for demo purpose) ProcessStartInfo processStartInfo = new ProcessStartInfo("result.pdf"); processStartInfo.UseShellExecute = true; Process.Start(processStartInfo); } } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine("Press enter key to exit..."); Console.ReadLine(); } }
protected void convertToPdfButton_Click(object sender, EventArgs e) { // Create a HTML to PDF converter object with default settings HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(); // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish htmlToPdfConverter.ConversionDelay = 2; string param1Name = param1NameTextBox.Text.Length > 0 ? param1NameTextBox.Text : "param1"; string param1Value = param1ValueTextBox.Text.Length > 0 ? param1ValueTextBox.Text : "Value 1"; string param2Name = param2NameTextBox.Text.Length > 0 ? param2NameTextBox.Text : "param2"; string param2Value = param2ValueTextBox.Text.Length > 0 ? param2ValueTextBox.Text : "Value 2"; string param3Name = param3NameTextBox.Text.Length > 0 ? param3NameTextBox.Text : "param3"; string param3Value = param3ValueTextBox.Text.Length > 0 ? param3ValueTextBox.Text : "Value 3"; string param4Name = param4NameTextBox.Text.Length > 0 ? param4NameTextBox.Text : "param4"; string param4Value = param4ValueTextBox.Text.Length > 0 ? param4ValueTextBox.Text : "Value 4"; string param5Name = param5NameTextBox.Text.Length > 0 ? param5NameTextBox.Text : "param5"; string param5Value = param5ValueTextBox.Text.Length > 0 ? param5ValueTextBox.Text : "Value 5"; string urlToConvert = urlTextBox.Text; if (postMethodRadioButton.Checked) { htmlToPdfConverter.HttpPostFields.Add(param1Name, param1Value); htmlToPdfConverter.HttpPostFields.Add(param2Name, param2Value); htmlToPdfConverter.HttpPostFields.Add(param3Name, param3Value); htmlToPdfConverter.HttpPostFields.Add(param4Name, param4Value); htmlToPdfConverter.HttpPostFields.Add(param5Name, param5Value); } else { Uri getMethodUri = new Uri(urlTextBox.Text); string query = getMethodUri.Query.Length > 0 ? "&" : "?" + String.Format("{0}={1}", param1Name, param1Value); query += String.Format("&{0}={1}", param2Name, param2Value); query += String.Format("&{0}={1}", param3Name, param3Value); query += String.Format("&{0}={1}", param4Name, param4Value); query += String.Format("&{0}={1}", param5Name, param5Value); urlToConvert = urlTextBox.Text + query; } // Convert the HTML page to a PDF document in a memory buffer byte[] outPdfBuffer = htmlToPdfConverter.ConvertUrl(urlToConvert); // Send the PDF as response to browser // Set response content type Response.AddHeader("Content-Type", "application/pdf"); // Instruct the browser to open the PDF file as an attachment or inline Response.AddHeader("Content-Disposition", String.Format("attachment; filename=GET_and_POST.pdf; size={0}", outPdfBuffer.Length.ToString())); // Write the PDF document buffer to HTTP response Response.BinaryWrite(outPdfBuffer); // End the HTTP response and stop the current page processing Response.End(); }
public ActionResult ConvertHtmlToPdf(IFormCollection collection) { // Create a HTML to PDF converter object with default settings HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(); // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish htmlToPdfConverter.ConversionDelay = 2; // Enable footer in the generated PDF document htmlToPdfConverter.PdfDocumentOptions.ShowFooter = true; // Optionally add a space between footer and the page body // Leave this option not set for no spacing htmlToPdfConverter.PdfDocumentOptions.BottomSpacing = float.Parse(collection["footerSpacingTextBox"]); // Set the footer height in points htmlToPdfConverter.PdfFooterOptions.FooterHeight = 50; // ----- Add HTML with Page Numbering to Footer ----- // Create a variable HTML element with page numbering string htmlStringWithPageNumbers = collection["htmlWithPageNumbersTextBox"]; string baseUrl = collection["baseUrlTextBox"]; HtmlToPdfVariableElement footerHtmlWithPageNumbers = new HtmlToPdfVariableElement(htmlStringWithPageNumbers, baseUrl); // Set the HTML element to fit the container height footerHtmlWithPageNumbers.FitHeight = true; // Add variable HTML element with page numbering to footer htmlToPdfConverter.PdfFooterOptions.AddElement(footerHtmlWithPageNumbers); // Optionally draw a line at the top of the footer if (collection["drawFooterLineCheckBox"].Count > 0) { // Calculate the footer width based on PDF page size and margins float footerWidth = htmlToPdfConverter.PdfDocumentOptions.PdfPageSize.Width - htmlToPdfConverter.PdfDocumentOptions.LeftMargin - htmlToPdfConverter.PdfDocumentOptions.RightMargin; // Create a line element for the top of the footer LineElement footerLine = new LineElement(0, 0, footerWidth, 0); // Set line color footerLine.ForeColor = Color.Gray; // Add line element to the bottom of the footer htmlToPdfConverter.PdfFooterOptions.AddElement(footerLine); } // Convert the HTML page to a PDF document in a memory buffer byte[] outPdfBuffer = htmlToPdfConverter.ConvertUrl(collection["urlTextBox"]); // Send the PDF file to browser FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf"); fileResult.FileDownloadName = "Page_Numbers_in_HTML.pdf"; return(fileResult); }
protected void convertToPdfButton_Click(object sender, EventArgs e) { // Get the server IP and port String serverIP = textBoxServerIP.Text; uint serverPort = uint.Parse(textBoxServerPort.Text); // Create a HTML to PDF converter object with default settings HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(serverIP, serverPort); // Set optional service password if (textBoxServicePassword.Text.Length > 0) { htmlToPdfConverter.ServicePassword = textBoxServicePassword.Text; } // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish htmlToPdfConverter.ConversionDelay = 2; // Convert a HTML page to a PDF document object Document pdfDocument = htmlToPdfConverter.ConvertUrlToPdfDocumentObject(urlTextBox.Text); string javaScript = null; if (alertMessageRadioButton.Checked) { // JavaScript to display an alert mesage javaScript = String.Format("app.alert(\"{0}\")", alertMessageTextBox.Text); } else if (printDialogRadioButton.Checked) { // JavaScript to open the print dialog javaScript = "print()"; } else if (zoomLevelRadioButton.Checked) { // JavaScript to set an initial zoom level javaScript = String.Format("zoom={0}", int.Parse(zoomLevelTextBox.Text)); } // Set the JavaScript action pdfDocument.OpenAction = new PdfActionJavaScript(javaScript); // Save the PDF document in a memory buffer byte[] outPdfBuffer = pdfDocument.Save(); // Send the PDF as response to browser // Set response content type Response.AddHeader("Content-Type", "application/pdf"); // Instruct the browser to open the PDF file as an attachment or inline Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Execute_Acrobat_JavaScript.pdf; size={0}", outPdfBuffer.Length.ToString())); // Write the PDF document buffer to HTTP response Response.BinaryWrite(outPdfBuffer); // End the HTTP response and stop the current page processing Response.End(); }
public async Task <dynamic> GenerateAct(BE.ReportBE.Report report, int type) { var assignment = _assignmentRepository.GetReportSupervisor(report.AssignmentId); var users = _assignmentRepository.GetByPersonnelIdAssignment(report.AssignmentId).ToList(); var usersClient = _assignmentRepository.GetContactByAssignemtnId(report.AssignmentId).ToList(); var supervisor = users.Where(x => x.UserType == 1).FirstOrDefault(); var technician = users.Where(x => x.UserType == 2).FirstOrDefault(); var client = usersClient.Where(x => x.Id == report.ContactId).FirstOrDefault(); var sValue = ConvertNumberToString(report.Value) + "\""; var pdfContent = string.Empty; if (type == 1) { pdfContent = Resources.Template.ActString.ToString(); } else if (type == 2) { pdfContent = Resources.Template.ExeString.ToString(); } CultureInfo ci = new CultureInfo("es-PE"); var colorStyle = sValue + " " + strFill.Replace("@@strcolor", strColor); pdfContent = pdfContent .Replace("@SocialName", assignment.CompanyName) .Replace("@RUC", assignment.RUC) .Replace("@Branch", assignment.CorpId) .Replace("@Description", assignment.Description) .Replace("@OT", assignment.WorkOrderNumber) .Replace("@Brand", assignment.Machine.Brand) .Replace("@Model", assignment.Machine.Model) .Replace("@Technical", technician?.Name) .Replace("@Horometro", assignment.Machine.TotalHoursFunction.ToString()) .Replace("@NumberSerie", assignment.Machine.SerialNumber) .Replace("@DateDelivery", report.Date.ToString("dd-MM-yyyy", ci)) .Replace("@DateService", assignment.RequestDate.ToString("dd-MM-yyyy", ci)) .Replace("@Antecedent", report.Antecedent) .Replace("@Work", report.Work) .Replace("@Observations", report.Observation) .Replace("@Recommendations", report.Replacement) .Replace("@Client", client?.Name + " " + client?.LastName) .Replace("@SignAct", report.UrlSign) .Replace(sValue.ToString(), colorStyle) //EXE .Replace("@Supervisor", supervisor?.Name) .Replace("@SPhone", supervisor?.Phone) .Replace("@SMail", supervisor?.Email); var converter = new HtmlToPdfConverter(); var pdfFile = converter.GeneratePdf(pdfContent); var path = System.IO.Path.GetTempPath(); dynamic dynamicAttachment = new ExpandoObject(); string pdfString = ""; string nameFile = ""; nameFile = report.Id + ".pdf"; if (type == 1) { pdfString = nameFile; } else if (type == 2) { pdfString = $"{path}\\" + nameFile; dynamicAttachment.Route = pdfString; System.IO.File.WriteAllBytes(pdfString, pdfFile); } string container = "act"; dynamicAttachment.File = pdfFile; dynamicAttachment.Container = container; dynamicAttachment.Name = nameFile; dynamicAttachment.Route = pdfString; dynamicAttachment.FileUrl = ""; var result = await StorageHelperAzure.UploadFileToAzure(dynamicAttachment , Constants.AzureStorage.DefaultConnectionString); dynamicAttachment.FileUrl = result.FileUrl; return(dynamicAttachment); }
protected void convertToPdfButton_Click(object sender, EventArgs e) { // Get the server IP and port String serverIP = textBoxServerIP.Text; uint serverPort = uint.Parse(textBoxServerPort.Text); // Create a HTML to PDF converter object with default settings HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(serverIP, serverPort); // Set optional service password if (textBoxServicePassword.Text.Length > 0) { htmlToPdfConverter.ServicePassword = textBoxServicePassword.Text; } // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish htmlToPdfConverter.ConversionDelay = 2; // Set the CSS selectors of the HTML elements before which to insert page breaks htmlToPdfConverter.PdfDocumentOptions.PageBreakBeforeHtmlElementsSelectors = new string[] { htmlElementsBeforeSelectorTextBox.Text }; // Set the CSS selectors of the HTML elements after which to insert page breaks htmlToPdfConverter.PdfDocumentOptions.PageBreakAfterHtmlElementsSelectors = new string[] { htmlElementsAfterSelectorTextBox.Text }; byte[] outPdfBuffer = null; if (convertHtmlRadioButton.Checked) { string htmlWithForm = htmlStringTextBox.Text; string baseUrl = baseUrlTextBox.Text; // Convert the HTML string to a PDF document in a memory buffer outPdfBuffer = htmlToPdfConverter.ConvertHtml(htmlWithForm, baseUrl); } else { string url = urlTextBox.Text; // Convert the HTML page to a PDF document in a memory buffer outPdfBuffer = htmlToPdfConverter.ConvertUrl(url); } // Send the PDF as response to browser // Set response content type Response.AddHeader("Content-Type", "application/pdf"); // Instruct the browser to open the PDF file as an attachment or inline Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Insert_Page_Breaks_Before_After_HTML_Elements_Using_API.pdf; size={0}", outPdfBuffer.Length.ToString())); // Write the PDF document buffer to HTTP response Response.BinaryWrite(outPdfBuffer); // End the HTTP response and stop the current page processing Response.End(); }
static void Main(string[] args) { try { Console.WriteLine("Please wait while PDF is being created..."); // Parse MessageContents using MsgReader Library // MsgReader library can be obtained from: https://github.com/Sicos1977/MSGReader using (var msg = new MsgReader.Outlook.Storage.Message("TxtSampleEmail.msg")) { // Get Sender information var from = msg.GetEmailSender(false, false); // Message sent datetime var sentOn = msg.SentOn; // Recipient To information var recipientsTo = msg.GetEmailRecipients(MsgReader.Outlook.RecipientType.To, false, false); // Recipient CC information var recipientsCc = msg.GetEmailRecipients(MsgReader.Outlook.RecipientType.Cc, false, false); #region Generate and save html // Get Html HtmlGenerator oHtmlGenerator = new HtmlGenerator(); oHtmlGenerator.Title = $"Subject: {msg.Subject}"; oHtmlGenerator.AddParagraphBodyItem($"File Name: {msg.FileName}"); oHtmlGenerator.AddParagraphBodyItem($"From: {from}"); oHtmlGenerator.AddParagraphBodyItem($"Sent On: {(sentOn.HasValue ? sentOn.Value.ToString("MM/dd/yyyy HH:mm") : "")}"); oHtmlGenerator.AddParagraphBodyItem($"To: {recipientsTo}"); oHtmlGenerator.AddParagraphBodyItem($"Subject: {msg.Subject}"); if (!string.IsNullOrEmpty(recipientsCc)) { oHtmlGenerator.AddParagraphBodyItem($"CC: {recipientsCc}"); } oHtmlGenerator.AddRawBodyItem("<hr/>"); var msgBodySplitted = msg.BodyText.Split("\n".ToCharArray()); foreach (var itmBody in msgBodySplitted) { oHtmlGenerator.AddParagraphBodyItem(itmBody); } // Generate Html oHtmlGenerator.SaveHtml("result.html"); #endregion using (HtmlToPdfConverter converter = new HtmlToPdfConverter()) { converter.PageSize = PaperKind.A4; converter.Orientation = Bytescout.PDF.Converters.PaperOrientation.Portrait; converter.ConvertHtmlToPdf("result.html", "result.pdf"); // Open result document in default associated application (for demo purpose) ProcessStartInfo processStartInfo = new ProcessStartInfo("result.pdf"); processStartInfo.UseShellExecute = true; Process.Start(processStartInfo); } } } catch (Exception ex) { Console.WriteLine(ex.Message); Console.WriteLine("Press enter key to exit..."); Console.ReadLine(); } }
public ActionResult Generate(GenerateViewModel viewModel) { var theDate = DateTime.ParseExact(viewModel.Date, "MM/dd/yyyy", CultureInfo.InvariantCulture).AddDays(1); var htmlToPdf = new HtmlToPdfConverter(); htmlToPdf.Size = PageSize.A3; if (!Directory.Exists(Server.MapPath(PathConstant.DerPath))) { Directory.CreateDirectory(Server.MapPath(PathConstant.DerPath)); } int revision = 0; var isExisted = _derService.IsDerExisted(theDate, out revision); revision = isExisted ? (revision + 1) : revision; var title = "DER/" + theDate.ToString("dd-MMM-yyyy"); var pdfName = string.Format("{0}_{1}.pdf", title.Replace('/', '-'), revision); var pdfPath = Path.Combine(Server.MapPath(PathConstant.DerPath), pdfName); var secretNumber = Guid.NewGuid().ToString(); var secretPath = Path.Combine(Server.MapPath(PathConstant.DerPath), secretNumber + ".txt"); System.IO.File.WriteAllText(secretPath, viewModel.Content); var displayUrl = Url.Action("Preview", "DerImage", new { secretNumber = secretNumber }, this.Request.Url.Scheme); htmlToPdf.Margins.Top = 20; htmlToPdf.Margins.Bottom = 20; htmlToPdf.Margins.Left = 20; htmlToPdf.Margins.Right = 20; htmlToPdf.GeneratePdfFromFile(displayUrl, null, pdfPath); var response = _derService.CreateOrUpdate(new CreateOrUpdateDerRequest { Filename = PathConstant.DerPath + "/" + pdfName, Title = title, Date = theDate, RevisionBy = UserProfile().UserId }); if (response.IsSuccess) { return RedirectToAction("Index"); } return base.ErrorPage(response.Message); //htmlToPdf.GeneratePdfFromFile(displayUrl, null, pdfPath); //return File(pdfPath, "application/pdf"); //var htmlToImageConverter = new HtmlToImageConverter(); //htmlToImageConverter.Height = 2481; //htmlToImageConverter.Width = 1754; //return File(htmlToImageConverter.GenerateImageFromFile(displayUrl, ImageFormat.Png), "image/png", "TheGraph.png"); }
protected void convertToPdfButton_Click(object sender, EventArgs e) { // Create a HTML to PDF converter object with default settings HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(); // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish htmlToPdfConverter.ConversionDelay = 2; Document pdfDocument = null; try { string htmlWithDigitalSignatureMarker = htmlStringTextBox.Text; string baseUrl = baseUrlTextBox.Text; // Convert a HTML string with a marker for digital signature to a PDF document object pdfDocument = htmlToPdfConverter.ConvertHtmlToPdfDocumentObject(htmlWithDigitalSignatureMarker, baseUrl); // Make the HTML element with 'digital_signature_element' mapping ID a link to digital signature properties HtmlElementMapping digitalSignatureMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("digital_signature_element"); if (digitalSignatureMapping != null) { PdfPage digitalSignaturePage = digitalSignatureMapping.PdfRectangles[0].PdfPage; RectangleF digitalSignatureRectangle = digitalSignatureMapping.PdfRectangles[0].Rectangle; string certificateFilePath = Server.MapPath("~/DemoAppFiles/Input/Certificates/evopdf.pfx"); // Get the certificate from password protected PFX file DigitalCertificatesCollection certificates = DigitalCertificatesStore.GetCertificates(certificateFilePath, "evopdf"); DigitalCertificate certificate = certificates[0]; // Create the digital signature DigitalSignatureElement signature = new DigitalSignatureElement(digitalSignatureRectangle, certificate); signature.Reason = "Protect the document from unwanted changes"; signature.ContactInfo = "The contact email is [email protected]"; signature.Location = "Development server"; digitalSignaturePage.AddElement(signature); } // Save the PDF document in a memory buffer byte[] outPdfBuffer = pdfDocument.Save(); // Send the PDF as response to browser // Set response content type Response.AddHeader("Content-Type", "application/pdf"); // Instruct the browser to open the PDF file as an attachment or inline Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Digital_Signatures.pdf; size={0}", outPdfBuffer.Length.ToString())); // Write the PDF document buffer to HTTP response Response.BinaryWrite(outPdfBuffer); // End the HTTP response and stop the current page processing Response.End(); } finally { // Close the PDF document if (pdfDocument != null) { pdfDocument.Close(); } } }
//HTML Conversion private void convertBtn_Click(object sender, EventArgs e) { //Initialize HTML converter HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.WebKit); //WebKit converter settings WebKitConverterSettings webKitSettings = new WebKitConverterSettings(); string urlToConvert = string.Empty; if (rdo_urlBtn.Checked) { if (this.openFileDialog1.FileName == string.Empty) { urlToConvert = url_TxtBox.Text; } else { urlToConvert = openFileDialog1.FileName; } } if (!IsUrlValid(urlToConvert) && urlToConvert != string.Empty) { if (MessageBox.Show("Please enter a valid URL", "Alert!!!", MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK) { url_TxtBox.Text = string.Empty; } } else { int delay = 0; if (int.TryParse(this.delay_txtBox.Text, out delay)) { //Set additional delay webKitSettings.AdditionalDelay = delay; //Assign the WebKit binaries path //webKitSettings.WebKitPath = @"../../QtBinaries"; //Enable javascript webKitSettings.EnableJavaScript = this.JavaScript_CheckBox.Checked; //HTML to PDF conversion if (this.rdo_PDFBtn.Checked) { //Enable hyperlink webKitSettings.EnableHyperLink = this.hyperlink_checkBox.Checked; //Enable bookmarks webKitSettings.EnableBookmarks = this.bookmark_checkBox.Checked; //Enble form webKitSettings.EnableForm = this.form_checkBox.Checked; //Enable toc webKitSettings.EnableToc = this.toc_checkBox.Checked; //Page rotation angle webKitSettings.PageRotateAngle = (PdfPageRotateAngle)Enum.Parse(typeof(PdfPageRotateAngle), this.rotation_comboBox.SelectedItem.ToString()); int margin = 0; if (int.TryParse(this.margin_comboBox.Text, out margin)) { //Set page margins webKitSettings.Margin.All = margin; //Set page orientation. if (this.rdo_portraitBtn.Checked) { webKitSettings.Orientation = PdfPageOrientation.Portrait; } else { webKitSettings.Orientation = PdfPageOrientation.Landscape; } //Adding Header if (this.header_checkBox.Checked) { webKitSettings.PdfHeader = this.AddHeader(webKitSettings.PdfPageSize.Width, "Syncfusion Essential PDF", " "); } //Adding Footer if (this.footer_checkBox.Checked) { webKitSettings.PdfFooter = this.AddFooter(webKitSettings.PdfPageSize.Width, "@Copyright 2015"); } htmlConverter.ConverterSettings = webKitSettings; PdfDocument document = null; try { if (rdo_urlBtn.Checked) { //Convert url to PDF document. document = htmlConverter.Convert(urlToConvert); } else { //Convert HTML string to PDF document document = htmlConverter.Convert(this.htmlString_txtBox.Text, this.baseURL_txtBox.Text); } // Save and close the document. document.Save("Sample.pdf"); document.Close(true); //Message box confirmation to view the created PDF document. if (MessageBox.Show("Do you want to view the PDF file?", "PDF File Created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { //Launching the PDF file using the default Application.[Acrobat Reader] System.Diagnostics.Process.Start("Sample.pdf"); this.Close(); } else { // Exit this.Close(); } } catch (PdfException ex) { if (MessageBox.Show("WebKit assemblies are missing", "Alert!!!", MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK) { } } } else { if (MessageBox.Show("Please enter a valid margin", "Alert!!!", MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK) { margin_comboBox.Text = "20"; } } } //HTML to SVG Conversion else if (this.rdo_SvgBtn.Checked) { //Assign the WebKit settings htmlConverter.ConverterSettings = webKitSettings; try { //Convert url to svg htmlConverter.ConvertToSvg(urlToConvert, "Sample.svg"); //Message box confirmation to view the created SVG document. if (MessageBox.Show("Do you want to view the SVG file?", "SVG File Created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { //Launching the SVG file using the default Application.[Default Browser] System.Diagnostics.Process.Start("Sample.svg"); this.Close(); } else { // Exit this.Close(); } } catch (PdfException ex) { if (MessageBox.Show("WebKit assemblies are missing", "Alert!!!", MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK) { } } } // HTML to Image Conversion else if (this.rdo_ImageBtn.Checked) { //Assign the WebKit settings htmlConverter.ConverterSettings = webKitSettings; try { Image[] images; if (this.rdo_urlBtn.Checked) { //Convert HTML to image images = htmlConverter.ConvertToImage(urlToConvert); } else { //Convert HTML string to image images = htmlConverter.ConvertToImage(this.htmlString_txtBox.Text, this.baseURL_txtBox.Text); } //Save the image images[0].Save("Sample.png", System.Drawing.Imaging.ImageFormat.Png); images[0].Dispose(); //Message box confirmation to view the created Image document. if (MessageBox.Show("Do you want to view the image file?", "Image File Created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { //Launching the Image file using the default Application.[Image viewer] System.Diagnostics.Process.Start("Sample.png"); this.Close(); } else { // Exit this.Close(); } } catch (PdfException ex) { if (MessageBox.Show("WebKit assemblies are missing", "Alert!!!", MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK) { } } } //HTML to MHTML conversion else { //Assign the WebKit settings htmlConverter.ConverterSettings = webKitSettings; try { //Convert url to mhtml htmlConverter.ConvertToMhtml(urlToConvert, "Sample.mhtml"); //Message box confirmation to view the created MHTML document. if (MessageBox.Show("Do you want to view the MHTML file?", "MHTML File Created", MessageBoxButtons.YesNo, MessageBoxIcon.Information) == DialogResult.Yes) { //Launching the MHTML file using the default Application.[Default browser] System.Diagnostics.Process.Start("Sample.mhtml"); this.Close(); } else { // Exit this.Close(); } } catch (PdfException ex) { if (MessageBox.Show("WebKit assemblies are missing", "Alert!!!", MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK) { } } } } else { if (MessageBox.Show("Please enter a valid delay", "Alert!!!", MessageBoxButtons.OK, MessageBoxIcon.Information) == DialogResult.OK) { delay_txtBox.Text = "0"; } } } }
protected void convertToPdfButton_Click(object sender, EventArgs e) { // Get the server IP and port String serverIP = textBoxServerIP.Text; uint serverPort = uint.Parse(textBoxServerPort.Text); // Create a HTML to PDF converter object with default settings HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(serverIP, serverPort); // Set optional service password if (textBoxServicePassword.Text.Length > 0) { htmlToPdfConverter.ServicePassword = textBoxServicePassword.Text; } // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish htmlToPdfConverter.ConversionDelay = 2; string htmlWithButton = htmlStringTextBox.Text; string baseUrl = baseUrlTextBox.Text; // Convert a HTML string with a button to a PDF document object Document pdfDocument = htmlToPdfConverter.ConvertHtmlToPdfDocumentObject(htmlWithButton, baseUrl); // Get the button location in PDF HtmlElementMapping buttonMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("javascript_button"); if (buttonMapping != null) { PdfPage buttonPdfPage = pdfDocument.GetPage(buttonMapping.PdfRectangles[0].PageIndex); RectangleFloat buttonRectangle = buttonMapping.PdfRectangles[0].Rectangle; // The font used for buttons text in PDF document PdfFont buttonTextFont = new PdfFont("Times New Roman", 8, true); // Create a PDF form button PdfFormButton pdfButton = new PdfFormButton(buttonRectangle, "Execute Acrobat JavaScript", buttonTextFont); pdfButton.Style.BackColor = RgbColor.Beige; pdfDocument.Form.AddButton(buttonPdfPage, pdfButton); // Set JavaScript action to be executed when the button is clicked string javaScript = null; if (alertMessageRadioButton.Checked) { // JavaScript to display an alert mesage javaScript = String.Format("app.alert(\"{0}\")", alertMessageTextBox.Text); } else if (printDialogRadioButton.Checked) { // JavaScript to open the print dialog javaScript = "print()"; } else if (zoomLevelRadioButton.Checked) { // JavaScript to set an initial zoom level javaScript = String.Format("zoom={0}", int.Parse(zoomLevelTextBox.Text)); } // Set the JavaScript action pdfButton.Action = new PdfActionJavaScript(javaScript); } // Save the PDF document in a memory buffer byte[] outPdfBuffer = pdfDocument.Save(); // Send the PDF as response to browser // Set response content type Response.AddHeader("Content-Type", "application/pdf"); // Instruct the browser to open the PDF file as an attachment or inline Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Button_JavaScript_Actions.pdf; size={0}", outPdfBuffer.Length.ToString())); // Write the PDF document buffer to HTTP response Response.BinaryWrite(outPdfBuffer); // End the HTTP response and stop the current page processing Response.End(); }
public ActionResult Receipt(int? id) { var workStream = new MemoryStream(); // get the record to which this registation id belongs to using (var session = NHibernateHelper.CreateSessionFactory()) { using (var transaction = session.BeginTransaction()) { // get the html template content var path = System.Web.Hosting.HostingEnvironment.MapPath("~/App_Data/templates/receipt.html"); var htmlContent = System.IO.File.ReadAllText(path); var registrations = new List<Renewal>(session.CreateCriteria(typeof(Renewal)).List<Renewal>()); var ts = new List<Transaction>(session.CreateCriteria(typeof(Transaction)).List<Transaction>()); var t = ts.FirstOrDefault(x => x.Id == id); var r = t.Renewal.Registration; // do string replacements to htmlContent here var parsedHtmlContent = htmlContent; // Head details if (r != null) { parsedHtmlContent = Replacement(parsedHtmlContent, "$$BootstrapCss$$", BootstrapCss); parsedHtmlContent = Replacement(parsedHtmlContent, "$$PHERMC_REG_NO$$", r.PhermcRegistrationNumber); var lastRenewalDate = r.LastRenewalDate == null || r.LastRenewalDate.Equals(DateTime.MinValue) ? "" : r.LastRenewalDate.Value.ToString("dd/MM/yyyy"); parsedHtmlContent = Replacement(parsedHtmlContent, "$$ESTABLISHMENT_NAME$$", r.EstablishmentName); parsedHtmlContent = Replacement(parsedHtmlContent, "$$CAC_NUMBER$$", r.CacNumber); parsedHtmlContent = Replacement(parsedHtmlContent, "$$REGISTRATION_DATE$$", r.RegistrationDate.ToString("dd/MM/yyyy")); // create $$TBODY_CONTENT$$ here var totalPaid = 0.0M; var tbodyRows = new StringBuilder(); var payments = t.Renewal.Transactions; if (payments.Any()) { foreach (var p in payments) { totalPaid += p.Amount; } } var lastPayment = t; var receiptTitle = "PAYMENT RECEIPT"; if (lastPayment.Printed) { receiptTitle = "COPY OF RECEIPT"; } parsedHtmlContent = Replacement(parsedHtmlContent, "$$RECEIPT_TITLE$$", receiptTitle); tbodyRows.Append("<tr>"); tbodyRows.AppendFormat("<td>{0}</td>", lastPayment.Date.ToString("dd/MM/yyyy")); tbodyRows.AppendFormat("<td>{0}</td>", lastPayment.PaymentType.Name); tbodyRows.AppendFormat("<td>{0}</td>", ""); tbodyRows.AppendFormat("<td>{0}</td>", lastPayment.ReceivedFrom); tbodyRows.AppendFormat("<td>{0}</td>", lastPayment.ReceivedBy.Username); tbodyRows.AppendFormat("<td class=\"right\">₦{0}</td>", lastPayment.Amount.ToString("#,##0.00")); tbodyRows.Append("</tr>"); parsedHtmlContent = Replacement(parsedHtmlContent, "$$TBODY_CONTENT$$", tbodyRows.ToString()); // Update totals parsedHtmlContent = Replacement(parsedHtmlContent, "$$TOTAL$$", lastPayment.Amount.ToString("N2")); parsedHtmlContent = Replacement(parsedHtmlContent, "$$TOTAL_DUE$$", t.Renewal.Amount.ToString("#,##0.00")); var amountOutstanding = t.Renewal.Amount - totalPaid; parsedHtmlContent = Replacement(parsedHtmlContent, "$$OUTSTANDING$$", amountOutstanding.ToString("#,##0.00")); // create instance of pdf api var htmlToPdf = new HtmlToPdfConverter(); // convert theget a byte array var pdfBytes = htmlToPdf.GeneratePdf(parsedHtmlContent); var byteInfo = pdfBytes; workStream.Write(byteInfo, 0, byteInfo.Length); workStream.Position = 0; lastPayment.Printed = true; transaction.Commit(); } } } return File(workStream, "application/pdf", string.Format("Receipt_{0}_{1}.pdf", id, DateTime.Now.ToString("yyyyMMddhhmmss"))); }
private void button2_Click(object sender, EventArgs e) { string printername = ""; PrintDialog pd = new PrintDialog(); if (pd.ShowDialog() == System.Windows.Forms.DialogResult.OK) { printername = pd.PrinterSettings.PrinterName; try { HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(); htmlToPdfConverter.LicenseKey = "sjwvPS4uPSskPSgzLT0uLDMsLzMkJCQk"; htmlToPdfConverter.HtmlViewerWidth = 850; htmlToPdfConverter.PdfDocumentOptions.AvoidImageBreak = true; byte[] outPdfBuffer = htmlToPdfConverter.ConvertHtml(winFormHtmlEditor1.DocumentHtml, ""); InputPdf inputPdf = new InputPdf(outPdfBuffer); //PrinterSettings settings = new PrinterSettings(); PrintJob printJob = new PrintJob(printername, inputPdf); printJob.DocumentName = ReportCombo.Text.Replace(" ", "_").Replace("/",""); PrintJob.AddLicense("FPM20NXDLB2DHPnggbYuVwkquSU3u2ffoA/Pgph4rjG5wiNCxO8yEfbLf2j90rZw1J3VJQF2tsniVvl5CxYka6SmZX4ak6keSsOg"); printJob.PrintOptions.Scaling = new AutoPageScaling(); printJob.Print(); } catch (Exception ee) { Logger.Instance.WriteToLog(ee.ToString()); } } }
internal HtmlToPdfConverter CreateWkConverter(PdfConvertSettings settings) { // Global options var converter = new HtmlToPdfConverter { Grayscale = settings.Grayscale, LowQuality = settings.LowQuality, Orientation = (PageOrientation)(int)settings.Orientation, PageHeight = settings.PageHeight, PageWidth = settings.PageWidth, Size = (PageSize)(int)settings.Size, PdfToolPath = FileSystemHelper.TempDir("wkhtmltopdf") }; if (settings.Margins != null) { converter.Margins.Bottom = settings.Margins.Bottom; converter.Margins.Left = settings.Margins.Left; converter.Margins.Right = settings.Margins.Right; converter.Margins.Top = settings.Margins.Top; } var sb = new StringBuilder(settings.CustomFlags); // doc title if (settings.Title.HasValue()) { sb.AppendFormat(CultureInfo.CurrentCulture, " --title \"{0}\"", settings.Title); } // Cover content & options if (settings.Cover != null) { var path = settings.Cover.Process("cover"); if (path.HasValue()) { sb.AppendFormat(" cover \"{0}\" ", path); settings.Cover.WriteArguments("cover", sb); if (settings.CoverOptions != null) { settings.CoverOptions.Process("cover", sb); } } } // Toc options if (settings.TocOptions != null && settings.TocOptions.Enabled) { settings.TocOptions.Process("toc", sb); } // apply cover & toc converter.CustomWkHtmlArgs = sb.ToString().Trim().NullEmpty(); sb.Clear(); // Page options if (settings.PageOptions != null) { settings.PageOptions.Process("page", sb); } // Header content & options if (settings.Header != null) { var path = settings.Header.Process("header"); if (path.HasValue()) { sb.AppendFormat(" --header-html \"{0}\"", path); settings.Header.WriteArguments("header", sb); } } if (settings.HeaderOptions != null && (settings.Header != null || settings.HeaderOptions.HasText)) { settings.HeaderOptions.Process("header", sb); } // Footer content & options if (settings.Footer != null) { var path = settings.Footer.Process("footer"); if (path.HasValue()) { sb.AppendFormat(" --footer-html \"{0}\"", path); settings.Footer.WriteArguments("footer", sb); } } if (settings.FooterOptions != null && (settings.Footer != null || settings.FooterOptions.HasText)) { settings.FooterOptions.Process("footer", sb); } // apply settings converter.CustomWkHtmlPageArgs = sb.ToString().Trim().NullEmpty(); return(converter); }
internal HtmlToPdfConverter CreateWkConverter(PdfConvertSettings settings) { // Global options var converter = new HtmlToPdfConverter { Grayscale = settings.Grayscale, LowQuality = settings.LowQuality, Orientation = (PageOrientation)(int)settings.Orientation, PageHeight = settings.PageHeight, PageWidth = settings.PageWidth, Size = (PageSize)(int)settings.Size, }; if (settings.Margins != null) { converter.Margins.Bottom = settings.Margins.Bottom; converter.Margins.Left = settings.Margins.Left; converter.Margins.Right = settings.Margins.Right; converter.Margins.Top = settings.Margins.Top; } var sb = new StringBuilder(settings.CustomFlags); // doc title if (settings.Title.HasValue()) { sb.AppendFormat(CultureInfo.CurrentCulture, " --title \"{0}\"", settings.Title); } // Cover content & options if (settings.Cover != null) { var path = settings.Cover.Process("cover"); if (path.HasValue()) { sb.AppendFormat(" cover \"{0}\" ", path); settings.Cover.WriteArguments("cover", sb); if (settings.CoverOptions != null) { settings.CoverOptions.Process("cover", sb); } } } // Toc options if (settings.TocOptions != null && settings.TocOptions.Enabled) { settings.TocOptions.Process("toc", sb); } // apply cover & toc converter.CustomWkHtmlArgs = sb.ToString().Trim().NullEmpty(); sb.Clear(); // Page options if (settings.PageOptions != null) { settings.PageOptions.Process("page", sb); } // Header content & options if (settings.Header != null) { var path = settings.Header.Process("header"); if (path.HasValue()) { sb.AppendFormat(" --header-html \"{0}\"", path); settings.Header.WriteArguments("header", sb); } } if (settings.HeaderOptions != null && (settings.Header != null || settings.HeaderOptions.HasText)) { settings.HeaderOptions.Process("header", sb); } // Footer content & options if (settings.Footer != null) { var path = settings.Footer.Process("footer"); if (path.HasValue()) { sb.AppendFormat(" --footer-html \"{0}\"", path); settings.Footer.WriteArguments("footer", sb); } } if (settings.FooterOptions != null && (settings.Footer != null || settings.FooterOptions.HasText)) { settings.FooterOptions.Process("footer", sb); } // apply settings converter.CustomWkHtmlPageArgs = sb.ToString().Trim().NullEmpty(); return converter; }
protected void convertToPdfButton_Click(object sender, EventArgs e) { // Create a HTML to PDF converter object with default settings HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(); // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Set an adddional delay in seconds to wait for JavaScript or AJAX calls after page load completed // Set this property to 0 if you don't need to wait for such asynchcronous operations to finish htmlToPdfConverter.ConversionDelay = 2; // Install a handler where you can set header and footer visibility or create a custom header and footer in each page htmlToPdfConverter.PrepareRenderPdfPageEvent += new PrepareRenderPdfPageDelegate(htmlToPdfConverter_PrepareRenderPdfPageEvent); // Add Header // Enable header in the generated PDF document htmlToPdfConverter.PdfDocumentOptions.ShowHeader = addHeaderCheckBox.Checked; // Optionally add a space between header and the page body // The spacing for first page and the subsequent pages can be set independently // Leave this option not set for no spacing htmlToPdfConverter.PdfDocumentOptions.Y = float.Parse(firstPageSpacingTextBox.Text); htmlToPdfConverter.PdfDocumentOptions.TopSpacing = float.Parse(headerSpacingTextBox.Text); // Draw header elements if (htmlToPdfConverter.PdfDocumentOptions.ShowHeader) { DrawHeader(htmlToPdfConverter, drawHeaderLineCheckBox.Checked); } // Add Footer // Enable footer in the generated PDF document htmlToPdfConverter.PdfDocumentOptions.ShowFooter = addFooterCheckBox.Checked; // Optionally add a space between footer and the page body // Leave this option not set for no spacing htmlToPdfConverter.PdfDocumentOptions.BottomSpacing = float.Parse(footerSpacingTextBox.Text); // Draw footer elements if (htmlToPdfConverter.PdfDocumentOptions.ShowFooter) { DrawFooter(htmlToPdfConverter, addPageNumbersInFooterCheckBox.Checked, drawFooterLineCheckBox.Checked); } // Convert the HTML page to a PDF document in a memory buffer byte[] outPdfBuffer = htmlToPdfConverter.ConvertUrl(urlTextBox.Text); // Send the PDF as response to browser // Set response content type Response.AddHeader("Content-Type", "application/pdf"); // Instruct the browser to open the PDF file as an attachment or inline Response.AddHeader("Content-Disposition", String.Format("attachment; filename=HTML_in_Header_Footer.pdf; size={0}", outPdfBuffer.Length.ToString())); // Write the PDF document buffer to HTTP response Response.BinaryWrite(outPdfBuffer); // End the HTTP response and stop the current page processing Response.End(); }
public IActionResult pdf(int id) { //Initialize HTML to PDF converter HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(); WebKitConverterSettings settings = new WebKitConverterSettings(); //Set WebKit path settings.WebKitPath = Path.Combine(hosting.ContentRootPath, "QtBinariesWindows"); //Assign WebKit settings to HTML converter htmlConverter.ConverterSettings = settings; //Convert URL to PDF Nomination mrki = _db.Nomination.Where(a => a.NominationId == id).Include(b => b.Applicant).ThenInclude(q => q.University).Include(b => b.Applicant).ThenInclude(c => c.ApplicationUser).ThenInclude(x => x.Country).FirstOrDefault(); PdfDocument pdfDocument = new PdfDocument(); //Add a page to the PDF document. PdfPage pdfPage = pdfDocument.Pages.Add(); //Create a PDF Template. PdfTemplate template = new PdfTemplate(900, 900); //Draw a rectangle on the template graphics template.Graphics.DrawRectangle(PdfBrushes.White, new Syncfusion.Drawing.RectangleF(0, 0, 900, 900)); PdfFont font = new PdfStandardFont(PdfFontFamily.Helvetica, 12); PdfFont font2 = new PdfStandardFont(PdfFontFamily.Helvetica, 20); PdfFont font3 = new PdfStandardFont(PdfFontFamily.Helvetica, 16); PdfBrush brush = new PdfSolidBrush(Color.Black); //Draw a string using the graphics of the template. RectangleF bounds = new RectangleF(0, 0, pdfDocument.Pages[0].GetClientSize().Width, 52); //dirao PdfPageTemplateElement header = new PdfPageTemplateElement(bounds); //Load the PDF document FileStream imageStream = new FileStream("unmo_logo.png", FileMode.Open, FileAccess.Read); PdfImage image = new PdfBitmap(imageStream); //Draw the image in the header. header.Graphics.DrawImage(image, new PointF(75, 0), new SizeF(137, 52)); header.Graphics.DrawString("Nomination number " + mrki.NominationId, font2, brush, 205, 12); //Add the header at the top. pdfDocument.Template.Top = header; template.Graphics.DrawString("Full name: ", font, brush, 32, 15); template.Graphics.DrawString(mrki.Applicant.ApplicationUser.Name + " " + mrki.Applicant.ApplicationUser.Surname, font, brush, 280, 15); template.Graphics.DrawString("Account created: ", font, brush, 32, 30); template.Graphics.DrawString(mrki.Applicant.CreatedProfile.ToString(), font, brush, 280, 30); template.Graphics.DrawString("Nomination created: ", font, brush, 32, 45); template.Graphics.DrawString(mrki.CreatedNom.ToString(), font, brush, 280, 45); template.Graphics.DrawString("Nomination submitted: ", font, brush, 32, 60); template.Graphics.DrawString(mrki.FinishedTime.ToString(), font, brush, 280, 60); template.Graphics.DrawString("Information", font3, brush, 10, 87); template.Graphics.DrawString("E-mail: ", font, brush, 32, 112); template.Graphics.DrawString(mrki.Applicant.ApplicationUser.Email.ToString(), font, brush, 280, 112); template.Graphics.DrawString("Phone number: ", font, brush, 32, 127); template.Graphics.DrawString(mrki.Applicant.ApplicationUser.PhoneNumber.ToString(), font, brush, 280, 127); template.Graphics.DrawString("Nationality: ", font, brush, 32, 142); template.Graphics.DrawString(mrki.Applicant.ApplicationUser.Country.Name.ToString(), font, brush, 280, 142); template.Graphics.DrawString("Faculty: ", font, brush, 32, 157); template.Graphics.DrawString(mrki.Applicant.FacultyName.ToString(), font, brush, 280, 157); template.Graphics.DrawString("University: ", font, brush, 32, 172); template.Graphics.DrawString(mrki.Applicant.University.Name.ToString(), font, brush, 280, 172); template.Graphics.DrawString("Student/staff: ", font, brush, 32, 187); template.Graphics.DrawString(mrki.Applicant.TypeOfApplication.ToString(), font, brush, 280, 187); var path1 = ""; if (mrki.LearningAgreement != null) { path1 = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.LearningAgreement); } else if (mrki.WorkPlan != null) { path1 = Path.Combine(Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.WorkPlan); } var path2 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.CV); var pathx = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.Passport); var path3 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.EngProficiency); var path4 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.TranscriptOfRecords); var path5 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.MotivationLetter); var path6 = Path.Combine( Directory.GetCurrentDirectory(), "wwwroot\\uploads\\", mrki.ReferenceLetter); FileStream stream1 = new FileStream(path1, FileMode.Open, FileAccess.Read); FileStream stream2 = new FileStream(path2, FileMode.Open, FileAccess.Read); FileStream streamx = new FileStream(pathx, FileMode.Open, FileAccess.Read); FileStream stream3 = new FileStream(path3, FileMode.Open, FileAccess.Read); FileStream stream4 = new FileStream(path4, FileMode.Open, FileAccess.Read); FileStream stream5 = new FileStream(path5, FileMode.Open, FileAccess.Read); // Creates a PDF stream for merging Stream[] streams = { stream1, stream2, stream3, streamx, stream4, stream5 }; // Merges PDFDocument. PdfDocumentBase.Merge(pdfDocument, streams); ////Draw the template on the page graphics of the document. pdfPage.Graphics.DrawPdfTemplate(template, PointF.Empty); //Save the document into stream MemoryStream stream = new MemoryStream(); pdfDocument.Save(stream); stream.Position = 0; pdfDocument.Close(true); //Define the file name FileStreamResult nova = new FileStreamResult(stream, "nomination/pdf"); string nameOfFile = "Nomination_" + mrki.NominationId + "_" + mrki.Applicant.ApplicationUser.Name + "_" + mrki.Applicant.ApplicationUser.Surname + ".pdf"; nova.FileDownloadName = nameOfFile; return(nova); }
public void A_Pdf_Is_Generated() { //Arange string html = @"<div class='row'> <div> <div> <table> <thead> <tr> <th></th> <th>titel</th> <th></th> </tr> </thead> <tbody> <tr> <td></td> <td>1</td> <td></td> </tr> </tbody> </table> </div> </div> <div> <div> <div> <div> Voornaam Achternaam </div> <div> <a>save</a> </div> </div> <div> <div> <h5>Omschrijving</h5> <table> <thead> <tr> <th>Omschrijving:</th> <th>Gewicht</th> <th>Score</th> <th>?</th> <th>---</th> </tr> </thead> <tbody> <tr> <td>doel omschrijving</td> <td>20</td> <td> <a>3</a> </td> <td> <div> Andere taak </div> </td> <td></td> </tr> <tr> <td>doel omschrijving</td> <td>20</td> <td> <a>3</a> </td> <td> <div> Afwezig </div> </td> <td></td> </tr> <tr> <td>doel omschrijving</td> <td>20</td> <td> <a>3</a> </td> <td> <div> Andere taak </div> </td> <td></td> </tr> </tbody> <tfoot> <tr> <td></td> <td></td> <td></td> <td></td> <td></td> </tr> </tfoot> </table> </div> <div>Totaal: ??</div> <div> <div> Opmerking:</div> <div> <textarea></textarea> </div> </div> </div> </div> </div> </div>"; string filename = @"C:\temp\pdftest.pdf"; var pdfConverter = new HtmlToPdfConverter(); pdfConverter.Orientation = PageOrientation.Landscape; //Act pdfConverter.GeneratePdf(html,null, filename); // bool success = SaveData(filename, pdfbytes); ////Assert //Assert.True(success); //Assert // no assert assert = no error }