/// <summary> /// Publishes a generic letter on School letterhead. PDF protection options are set via the boolean properties of this object. /// Document is digitally signed using a certificate generated by the local certificate authority in the dublinschool.org domain. /// </summary> /// <param name="bodyHtml">Body of the letter.</param> /// <param name="signerId">Employee id of the Faculty who will put their signature on the document. (automatically adds the signature image to the end of the document.</param> public Document PublishGenericLetter(String bodyHtml, bool digitallySign = false, int signerId = -1) { String html = Template.Replace("{content}", bodyHtml).Replace("{signature}", signerId == -1? "" : SignatureImage(signerId)); Document document = PdfConverter.ConvertHtmlToPdfDocumentObject(html, BaseURL, BaseURL); if (digitallySign) { try { /// digitally sign the document. HtmlElementMapping dsMap = PdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("digital_signature_element"); if (dsMap != null) { PdfPage page = dsMap.PdfRectangles.Last().PdfPage; RectangleF rectangle = dsMap.PdfRectangles.Last().Rectangle; DigitalCertificate cert = DocumentSigningCertificate; DigitalSignatureElement dse = new DigitalSignatureElement(rectangle, cert); dse.Reason = "Ensure Document Integrity and Protect from unwanted changes."; dse.ContactInfo = "Contact Email: [email protected]"; dse.Location = "Issuing Web Server"; page.AddElement(dse); } } catch (Exception e) { //WebhostEventLog.CommentLog.LogError("Failed to Apply digital signature to document...{0}{1}", Environment.NewLine, e.Message); } } return(document); }
public ActionResult CreatePdf(IFormCollection collection) { // Create a PDF document Document pdfDocument = new Document(); // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode pdfDocument.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Add a page to PDF document PdfPage pdfPage = pdfDocument.AddPage(); try { string htmlWithDigitalSignatureMarker = collection["htmlStringTextBox"]; string baseUrl = collection["baseUrlTextBox"]; // Add a HTML string with a marker for digital signature to PDF document HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement(htmlWithDigitalSignatureMarker, baseUrl); pdfPage.AddElement(htmlToPdfElement); // Make the HTML element with 'digital_signature_element' mapping ID a link to digital signature properties HtmlElementMapping digitalSignatureMapping = htmlToPdfElement.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("digital_signature_element"); if (digitalSignatureMapping != null) { PdfPage digitalSignaturePage = digitalSignatureMapping.PdfRectangles[0].PdfPage; RectangleF digitalSignatureRectangle = digitalSignatureMapping.PdfRectangles[0].Rectangle; string certificateFilePath = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/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 file to browser FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf"); fileResult.FileDownloadName = "Digital_Signatures.pdf"; return(fileResult); } finally { // Close the PDF document pdfDocument.Close(); } }
protected void convertToPdfButton_Click(object sender, EventArgs e) { // Create a PDF document Document pdfDocument = new Document(); // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode pdfDocument.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Add a page to PDF document PdfPage pdfPage = pdfDocument.AddPage(); try { string htmlWithDigitalSignatureMarker = htmlStringTextBox.Text; string baseUrl = baseUrlTextBox.Text; // Add a HTML string with a marker for digital signature to PDF document HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement(htmlWithDigitalSignatureMarker, baseUrl); pdfPage.AddElement(htmlToPdfElement); // Make the HTML element with 'digital_signature_element' mapping ID a link to digital signature properties HtmlElementMapping digitalSignatureMapping = htmlToPdfElement.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 pdfDocument.Close(); } }
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 htmlWithLinksAndAttachMarkers = htmlStringTextBox.Text; string baseUrl = baseUrlTextBox.Text; // Convert a HTML string with markers for file links and attachments to a PDF document object Document pdfDocument = htmlToPdfConverter.ConvertHtmlToPdfDocumentObject(htmlWithLinksAndAttachMarkers, baseUrl); // Make the HTML element with 'text_note' mapping ID a text note HtmlElementMapping textNoteMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("text_note"); if (textNoteMapping != null) { PdfPage textNotePage = pdfDocument.GetPage(textNoteMapping.PdfRectangles[0].PageIndex); RectangleFloat textNoteRectangle = textNoteMapping.PdfRectangles[0].Rectangle; // Create the text note TextNoteElement textNoteElement = new TextNoteElement(textNoteRectangle, "This is an initially closed text note"); textNoteElement.NoteIcon = TextNoteIcon.Note; textNoteElement.Open = false; textNotePage.AddElement(textNoteElement); } // Make the HTML element with 'text_note_opened' mapping ID an initially opened text note HtmlElementMapping textNoteOpenedMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("text_note_opened"); if (textNoteOpenedMapping != null) { PdfPage textNoteOpenedPage = pdfDocument.GetPage(textNoteMapping.PdfRectangles[0].PageIndex); RectangleFloat textNoteOpenedRectangle = textNoteOpenedMapping.PdfRectangles[0].Rectangle; // Create the text note TextNoteElement textNoteOpenedElement = new TextNoteElement(textNoteOpenedRectangle, "This is an initially opened text note"); textNoteOpenedElement.NoteIcon = TextNoteIcon.Note; textNoteOpenedElement.Open = true; textNoteOpenedPage.AddElement(textNoteOpenedElement); } // Make the HTML element with 'help_note' mapping ID a help note HtmlElementMapping helpNoteMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("help_note"); if (helpNoteMapping != null) { PdfPage helpNotePage = pdfDocument.GetPage(textNoteMapping.PdfRectangles[0].PageIndex); RectangleFloat helpNoteRectangle = helpNoteMapping.PdfRectangles[0].Rectangle; // Create the text note TextNoteElement helpNoteElement = new TextNoteElement(helpNoteRectangle, "This is an initially closed help note"); helpNoteElement.NoteIcon = TextNoteIcon.Help; helpNoteElement.Open = false; helpNotePage.AddElement(helpNoteElement); } // Make the HTML element with 'help_note_opened' mapping ID an initially opened help note HtmlElementMapping helpNoteOpenedMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("help_note_opened"); if (helpNoteOpenedMapping != null) { PdfPage helpNoteOpenedPage = pdfDocument.GetPage(textNoteMapping.PdfRectangles[0].PageIndex); RectangleFloat helpNoteOpenedRectangle = helpNoteOpenedMapping.PdfRectangles[0].Rectangle; // Create the text note TextNoteElement helpNoteOpenedElement = new TextNoteElement(helpNoteOpenedRectangle, "This is an initially opened help note"); helpNoteOpenedElement.NoteIcon = TextNoteIcon.Help; helpNoteOpenedElement.Open = true; helpNoteOpenedPage.AddElement(helpNoteOpenedElement); } // Make the HTML element with 'comment_note' mapping ID a comment note HtmlElementMapping commentNoteMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("comment_note"); if (commentNoteMapping != null) { PdfPage commentNotePage = pdfDocument.GetPage(textNoteMapping.PdfRectangles[0].PageIndex); RectangleFloat commentNoteRectangle = commentNoteMapping.PdfRectangles[0].Rectangle; // Create the text note TextNoteElement commentNoteElement = new TextNoteElement(commentNoteRectangle, "This is an initially closed comment note"); commentNoteElement.NoteIcon = TextNoteIcon.Comment; commentNoteElement.Open = false; commentNotePage.AddElement(commentNoteElement); } // Make the HTML element with 'comment_note_opened' mapping ID an initially opened comment note HtmlElementMapping commentNoteOpenedMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("comment_note_opened"); if (commentNoteOpenedMapping != null) { PdfPage commentNoteOpenedPage = pdfDocument.GetPage(textNoteMapping.PdfRectangles[0].PageIndex); RectangleFloat commentNoteOpenedRectangle = commentNoteOpenedMapping.PdfRectangles[0].Rectangle; // Create the text note TextNoteElement commentNoteOpenedElement = new TextNoteElement(commentNoteOpenedRectangle, "This is an initially opened comment note"); commentNoteOpenedElement.NoteIcon = TextNoteIcon.Comment; commentNoteOpenedElement.Open = true; commentNoteOpenedPage.AddElement(commentNoteOpenedElement); } // Make the HTML element with 'paragraph_note' mapping ID a paragraph note HtmlElementMapping paragraphNoteMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("paragraph_note"); if (paragraphNoteMapping != null) { PdfPage paragraphNotePage = pdfDocument.GetPage(textNoteMapping.PdfRectangles[0].PageIndex); RectangleFloat paragraphNoteRectangle = paragraphNoteMapping.PdfRectangles[0].Rectangle; // Create the text note TextNoteElement paragraphNoteElement = new TextNoteElement(paragraphNoteRectangle, "This is an initially closed paragraph note"); paragraphNoteElement.NoteIcon = TextNoteIcon.Paragraph; paragraphNoteElement.Open = false; paragraphNotePage.AddElement(paragraphNoteElement); } // Make the HTML element with 'new_paragraph_note' mapping ID a new paragraph note HtmlElementMapping newParagraphNoteMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("new_paragraph_note"); if (newParagraphNoteMapping != null) { PdfPage newParagraphNotePage = pdfDocument.GetPage(textNoteMapping.PdfRectangles[0].PageIndex); RectangleFloat newParagraphNoteRectangle = newParagraphNoteMapping.PdfRectangles[0].Rectangle; // Create the text note TextNoteElement newParagraphNoteElement = new TextNoteElement(newParagraphNoteRectangle, "This is an initially closed new paragraph note"); newParagraphNoteElement.NoteIcon = TextNoteIcon.NewParagraph; newParagraphNoteElement.Open = false; newParagraphNotePage.AddElement(newParagraphNoteElement); } // Make the HTML element with 'key_note' mapping ID a key note HtmlElementMapping keyNoteMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("key_note"); if (keyNoteMapping != null) { PdfPage keyNotePage = pdfDocument.GetPage(textNoteMapping.PdfRectangles[0].PageIndex); RectangleFloat keyNoteRectangle = keyNoteMapping.PdfRectangles[0].Rectangle; // Create the text note TextNoteElement keyNoteElement = new TextNoteElement(keyNoteRectangle, "This is an initially closed key note"); keyNoteElement.NoteIcon = TextNoteIcon.Key; keyNoteElement.Open = false; keyNotePage.AddElement(keyNoteElement); } // 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=Text_Notes.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; // Select the HTML elements for which to retrieve location and other information from HTML document htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors = new string[] { htmlElementsSelectorTextBox.Text }; // Convert HTML page to a PDF document object which can be further modified to highlight the selected elements Document pdfDocument = htmlToPdfConverter.ConvertUrlToPdfDocumentObject(urlTextBox.Text); // Highlight the selected elements in PDF with colored rectangles for (int i = 0; i < htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.Count; i++) { HtmlElementMapping htmlElementInfo = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetByIndex(i); // 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 (PdfRectangle htmlElementLocationInPdf in htmlElementInfo.PdfRectangles) { // Get the HTML element location in PDF page PdfPage htmlElementPdfPage = pdfDocument.GetPage(htmlElementLocationInPdf.PageIndex); RectangleFloat 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 = RgbColor.Blue; } else if (htmlElementTagName.ToLower() == "h2") { highlightRectangle.ForeColor = RgbColor.Green; } else if (htmlElementTagName.ToLower() == "h3") { highlightRectangle.ForeColor = RgbColor.Red; } else if (htmlElementTagName.ToLower() == "h4") { highlightRectangle.ForeColor = RgbColor.Yellow; } else if (htmlElementTagName.ToLower() == "h5") { highlightRectangle.ForeColor = RgbColor.Indigo; } else if (htmlElementTagName.ToLower() == "h6") { highlightRectangle.ForeColor = RgbColor.Orange; } else { highlightRectangle.ForeColor = RgbColor.Navy; } highlightRectangle.LineStyle.LineDashStyle = LineDashStyle.Solid; htmlElementPdfPage.AddElement(highlightRectangle); } } // 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=Select_in_API_HTML_Elements_to_Retrieve.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; string htmlWithLinksAndAttachMarkers = htmlStringTextBox.Text; string baseUrl = baseUrlTextBox.Text; // Convert a HTML string with markers for file links and attachments to a PDF document object Document pdfDocument = htmlToPdfConverter.ConvertHtmlToPdfDocumentObject(htmlWithLinksAndAttachMarkers, baseUrl); // Display the attachments panel when the PDF document is opened in a PDF viewer pdfDocument.ViewerPreferences.PageMode = ViewerPageMode.UseAttachments; // Create File Attachments // Create an attachment from a file without icon string fileAttachmentPath = Server.MapPath("~/DemoAppFiles/Input/Attach_Files/Attachment_File.txt"); pdfDocument.AddFileAttachment(fileAttachmentPath, "Attachment from File"); // Create an attachment from a stream without icon string fileStreamAttachmentPath = Server.MapPath("~/DemoAppFiles/Input/Attach_Files/Attachment_Stream.txt"); byte[] attachmentData = System.IO.File.ReadAllBytes(fileStreamAttachmentPath); pdfDocument.AddFileAttachment(attachmentData, "Attachment_Stream.txt", "Attachment from Stream"); // Create an attachment from file with paperclip icon in PDF HtmlElementMapping attachFromFileIconMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("attach_from_file_icon"); if (attachFromFileIconMapping != null) { PdfPage attachFromFilePage = pdfDocument.GetPage(attachFromFileIconMapping.PdfRectangles[0].PageIndex); RectangleFloat attachFromFileIconRectangle = attachFromFileIconMapping.PdfRectangles[0].Rectangle; string fileAttachmentWithIconPath = Server.MapPath("~/DemoAppFiles/Input/Attach_Files/Attachment_File_Icon.txt"); // Create the attachment from file FileAttachmentElement attachFromFileElement = new FileAttachmentElement(attachFromFileIconRectangle, fileAttachmentWithIconPath); attachFromFileElement.IconType = FileAttachmentIcon.Paperclip; attachFromFileElement.Text = "Attachment from File with Paperclip Icon"; attachFromFileElement.IconColor = RgbColor.Blue; attachFromFilePage.AddElement(attachFromFileElement); } // Create an attachment from stream with pushpin icon in PDF byte[] attachmentDataWithIcon = null; HtmlElementMapping attachFromStreamIconMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("attach_from_stream_icon"); if (attachFromStreamIconMapping != null) { PdfPage attachFromStreamPage = pdfDocument.GetPage(attachFromStreamIconMapping.PdfRectangles[0].PageIndex); RectangleFloat attachFromStreamIconRectangle = attachFromStreamIconMapping.PdfRectangles[0].Rectangle; string fileStreamAttachmentWithIconPath = Server.MapPath("~/DemoAppFiles/Input/Attach_Files/Attachment_Stream_Icon.txt"); attachmentDataWithIcon = System.IO.File.ReadAllBytes(fileStreamAttachmentWithIconPath); // Create the attachment from stream FileAttachmentElement attachFromStreamElement = new FileAttachmentElement(attachFromStreamIconRectangle, attachmentDataWithIcon, "Attachment_Stream_Icon.txt"); attachFromStreamElement.IconType = FileAttachmentIcon.PushPin; attachFromStreamElement.Text = "Attachment from Stream with Pushpin Icon"; attachFromStreamElement.IconColor = RgbColor.Green; attachFromStreamPage.AddElement(attachFromStreamElement); } // 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=File_Links_and_Attachments.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 { string htmlWithButton = collection["htmlStringTextBox"]; string baseUrl = collection["baseUrlTextBox"]; // Convert a HTML string with a button to a PDF document object pdfDocument = htmlToPdfConverter.ConvertHtmlToPdfDocumentObject(htmlWithButton, baseUrl); // Get the button location in PDF HtmlElementMapping buttonMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("javascript_button"); if (buttonMapping != null) { PdfPage buttonPdfPage = buttonMapping.PdfRectangles[0].PdfPage; RectangleF buttonRectangle = buttonMapping.PdfRectangles[0].Rectangle; // The font used for buttons text in PDF document PdfFont buttonTextFont = pdfDocument.AddFont(new Font("Times New Roman", 8, FontStyle.Regular, GraphicsUnit.Point)); // Create a PDF form button PdfFormButton pdfButton = pdfDocument.Form.AddButton(buttonPdfPage, buttonRectangle, "Execute Acrobat JavaScript", buttonTextFont); // Set JavaScript action to be executed when the button is clicked string javaScript = null; if (collection["JavaScriptAction"] == "alertMessageRadioButton") { // JavaScript to display an alert mesage javaScript = String.Format("app.alert(\"{0}\")", collection["alertMessageTextBox"]); } else if (collection["JavaScriptAction"] == "printDialogRadioButton") { // JavaScript to open the print dialog javaScript = "print()"; } else if (collection["JavaScriptAction"] == "zoomLevelRadioButton") { // JavaScript to set an initial zoom level javaScript = String.Format("zoom={0}", int.Parse(collection["zoomLevelTextBox"])); } // Set the JavaScript action pdfButton.Action = new PdfActionJavaScript(javaScript); } // 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 = "Button_JavaScript_Actions.pdf"; return(fileResult); } finally { // Close the PDF document if (pdfDocument != null) { pdfDocument.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; Document pdfDocument = null; try { string htmlWithDigitalSignatureMarker = collection["htmlStringTextBox"]; string baseUrl = collection["baseUrlTextBox"]; // 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 = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/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 file to browser FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf"); fileResult.FileDownloadName = "Digital_Signatures.pdf"; return(fileResult); } finally { // Close the PDF document if (pdfDocument != null) { pdfDocument.Close(); } } }
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(); }
protected void convertToPdfButton_Click(object sender, EventArgs e) { // Create a PDF document Document pdfDocument = new Document(); // Set license key received after purchase to use the converter in licensed mode // Leave it not set to use the converter in demo mode pdfDocument.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Add a page to PDF document PdfPage pdfPage = pdfDocument.AddPage(); try { string htmlWithButton = htmlStringTextBox.Text; string baseUrl = baseUrlTextBox.Text; // Add a HTML string with a button to PDF document HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement(htmlWithButton, baseUrl); pdfPage.AddElement(htmlToPdfElement); // Get the button location in PDF HtmlElementMapping buttonMapping = htmlToPdfElement.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("javascript_button"); if (buttonMapping != null) { PdfPage buttonPdfPage = buttonMapping.PdfRectangles[0].PdfPage; RectangleF buttonRectangle = buttonMapping.PdfRectangles[0].Rectangle; // The font used for buttons text in PDF document PdfFont buttonTextFont = pdfDocument.AddFont(new Font("Times New Roman", 8, FontStyle.Regular, GraphicsUnit.Point)); // Create a PDF form button PdfFormButton pdfButton = pdfDocument.Form.AddButton(buttonPdfPage, buttonRectangle, "Execute Acrobat JavaScript", buttonTextFont); // 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(); } finally { // Close the PDF document pdfDocument.Close(); } }
/// <summary> /// Function Creates PDF from HTML WITH TOC and Header-Footer /// </summary> /// <param name="PDFPath"></param> private void CreatePDF(string PDFPath) { #region Private Variables PdfConverter pdfConverter = new PdfConverter(); int mappingsTableIdx = 0; Document document = new Document(); //New document to be used for adding blank pages Document mergedDocument = new Document(); //New Document to merge Header and Pdfdocument string coverImg = string.Empty; float tocEntryMaxRight = 0.0f; int cntAddIndxForPage = 0; List<string> lstHeader = new List<string>(); int pageNum = 0; string strHeader = string.Empty; List<int> lstBlankPage = new List<int>(); #endregion // show the bookmarks when the document is opened pdfConverter.PdfViewerPreferences.PageMode = ViewerPageMode.UseNone; // set page margins pdfConverter.PdfDocumentOptions.TopMargin = 20; pdfConverter.PdfDocumentOptions.BottomMargin = 20; pdfConverter.PdfDocumentOptions.LeftMargin = 20; pdfConverter.PdfDocumentOptions.RightMargin = 20; pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.Letter11x17; pdfConverter.PdfDocumentOptions.FitWidth = false; pdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait; pdfConverter.AvoidImageBreak = true; pdfConverter.AvoidTextBreak = true; // Inform the converter about the HTML elements for which we want the location in PDF // The HTML ID of each entry in the table of contents is of form TOCEntry_{EntryIndex}_ID // the HTML ID of each target of a table of contents entry is of form TOCEntry_{EntryIndex}_Target_ID // Both toc entries and toc entries targets locations in PDF will be retrieved // and therefore the number of IDs is twice TOC entries number pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors = new string[2 * countTOC]; for (int tocEntryIndex = 1; tocEntryIndex <= countTOC; tocEntryIndex++) { // add the HTML ID of the TOC entry element to the list of elements for which we want the PDF location string tocEntryID = String.Format(PDFConstants.Instance.TOCENTRYID, tocEntryIndex); pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors[mappingsTableIdx++] = tocEntryID; // add the HTML ID of the TOC entry target element to the list of elements for which we want the PDF location string tocEntryTargetID = String.Format(PDFConstants.Instance.TOCTARGETID , tocEntryIndex); pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors[mappingsTableIdx++] = tocEntryTargetID; } // set bookmark options pdfConverter.PdfBookmarkOptions.HtmlElementSelectors = new string[] { PDFConstants.Instance.HTMLBookmarkTag }; // the URL of the HTML document to convert string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri; string htmlBookFilePath = Path.Combine(HttpContext.Current.Server.MapPath("~/data"), "temp.html"); // show header in rendered PDF pdfConverter.PdfDocumentOptions.ShowHeader = true; //Add pages to header Document coverImg = Path.Combine(HttpContext.Current.Server.MapPath("~/Images"), "Cover.jpg"); Document header = pdfConverter.GetPdfDocumentObjectFromHtmlString(string.Format(PDFConstants.Instance.HTMLCoverImageTag,coverImg ) + PDFConstants.Instance. HTMLMETAContentTag); // call the converter and get a Document object from URL Document pdfDocument = pdfConverter.GetPdfDocumentObjectFromUrl(htmlBookFilePath); pdfDocument.ViewerPreferences.CenterWindow = true; // Create a font used to write the page numbers in the table of contents PdfFont pageNumberFont = pdfDocument.Fonts.Add(new Font("Times New Roman", PAGE_NUMBER_FONT_SIZE, FontStyle.Regular, GraphicsUnit.Point), true); #region Generate TOC & Add to PDF // get the right edge of the table of contents where to position the page numbers for (int tocEntryIdx = 1; tocEntryIdx <= countTOC; tocEntryIdx++) { string tocEntryID = String.Format("TOCEntry_{0}_ID", tocEntryIdx); HtmlElementMapping tocEntryLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryID); if (tocEntryLocation != null) { if (tocEntryLocation.PdfRectangles[0].Rectangle.Right > tocEntryMaxRight) tocEntryMaxRight = tocEntryLocation.PdfRectangles[0].Rectangle.Right; } } // Add page number for each entry in the table of contents for (int tocEntryIdx = 1; tocEntryIdx <= countTOC; tocEntryIdx++) { string tocEntryID = String.Format("TOCEntry_{0}_ID", tocEntryIdx); string tocEntryTargetID = String.Format("TOCEntry_{0}_Target_ID", tocEntryIdx); HtmlElementMapping tocEntryLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryID); HtmlElementMapping tocEntryTargetLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryTargetID); // get the TOC entry page and bounds PdfPage tocEntryPdfPage = pdfDocument.Pages[tocEntryLocation.PdfRectangles[0].PageIndex]; RectangleF tocEntryPdfRectangle = tocEntryLocation.PdfRectangles[0].Rectangle; if (tocEntryLocation.HtmlElementCssClassName.Equals("h1")) { while (pageNum < tocEntryTargetLocation.PdfRectangles[0].PageIndex + 1 + cntAddIndxForPage) { pageNum++; lstHeader.Add(strHeader); } if ((tocEntryTargetLocation.PdfRectangles[0].PageIndex + 1 + cntAddIndxForPage) % 2 == 0) { pdfDocument.Pages.Insert(tocEntryTargetLocation.PdfRectangles[0].PageIndex + cntAddIndxForPage, document.AddPage(PageSize.Letter11x17, Margins.Empty)); lstBlankPage.Add(tocEntryTargetLocation.PdfRectangles[0].PageIndex + cntAddIndxForPage + 1); cntAddIndxForPage++; } strHeader = tocEntryLocation.HtmlElementText; } // get the page number of target where the TOC entry points int tocEntryTargetPageNumber = tocEntryTargetLocation.PdfRectangles[0].PageIndex + 1 + cntAddIndxForPage; // add dashed line from text entry to the page number LineElement lineToNumber = new LineElement(tocEntryPdfRectangle.Right + 5, tocEntryPdfRectangle.Y + tocEntryPdfRectangle.Height / 1.2F, tocEntryMaxRight + 200, tocEntryPdfRectangle.Y + tocEntryPdfRectangle.Height / 1.2F); lineToNumber.LineStyle.LineWidth = 1; lineToNumber.LineStyle.LineDashStyle = LineDashStyle.Dot; lineToNumber.ForeColor = Color.Black; tocEntryPdfPage.AddElement(lineToNumber); // create the page number text element to the right of the TOC entry TextElement pageNumberTextEement = new TextElement(tocEntryMaxRight + 205, tocEntryPdfRectangle.Y, -1, tocEntryPdfRectangle.Height, tocEntryTargetPageNumber.ToString(), pageNumberFont); pageNumberTextEement.TextAlign = HorizontalTextAlign.Left; pageNumberTextEement.VerticalTextAlign = VerticalTextAlign.Middle; pageNumberTextEement.ForeColor = Color.Black; // add the page number to the right of the TOC entry tocEntryPdfPage.AddElement(pageNumberTextEement); } #endregion #region Create index at End of the Document int TOC_INDEX_COUNT = NewIndexList.Count; pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors = new string[2 * TOC_INDEX_COUNT]; int mappingsEntryTableIdx = 0; for (int tocEntryIndex = 1; tocEntryIndex <= TOC_INDEX_COUNT; tocEntryIndex++) { // add the HTML ID of the TOC entry element to the list of elements for which we want the PDF location string tocEntryID = String.Format("#TOCIndex_{0}_ID", NewIndexList[tocEntryIndex - 1].ToString()); pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors[mappingsEntryTableIdx++] = tocEntryID; string tocEntryTargetID = String.Format("#TOCIndex_{0}_Target_ID", NewIndexList[tocEntryIndex - 1].ToString()); pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors[mappingsEntryTableIdx++] = tocEntryTargetID; } // call the converter and get a Document object from URL Document pdfDocumentI = pdfConverter.GetPdfDocumentObjectFromUrl(htmlBookFilePath); // Create a font used to write the page numbers in the table of contents PdfFont pageNumberFontI = pdfDocument.Fonts.Add(new Font("Arial", PAGE_NUMBER_FONT_SIZE, FontStyle.Bold, GraphicsUnit.Point), true); // get the right edge of the Index where to position the page numbers float tocEntryMaxRightI = 0.0f; for (int tocEntryIdx = 1; tocEntryIdx <= TOC_INDEX_COUNT; tocEntryIdx++) { string tocEntryID = String.Format("TOCIndex_{0}_ID", tocEntryIdx); HtmlElementMapping tocEntryLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryID); if (tocEntryLocation != null) { if (tocEntryLocation.PdfRectangles[0].Rectangle.Right > tocEntryMaxRightI) tocEntryMaxRightI = tocEntryLocation.PdfRectangles[0].Rectangle.Right; } } // Add page number for each entry in the Index for (int tocEntryIdx = 1; tocEntryIdx <= TOC_INDEX_COUNT; tocEntryIdx++) { string tocEntryID = String.Format("TOCIndex_{0}_ID", NewIndexList[tocEntryIdx - 1].ToString()); string tocEntryTargetID = String.Format("TOCIndex_{0}_Target_ID", NewIndexList[tocEntryIdx - 1].ToString()); HtmlElementMapping tocEntryLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryID); HtmlElementMapping tocEntryTargetLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryTargetID); // get the TOC entry page and bounds PdfPage tocEntryPdfPage = pdfDocument.Pages[tocEntryLocation.PdfRectangles[0].PageIndex + cntAddIndxForPage]; RectangleF tocEntryPdfRectangle = tocEntryLocation.PdfRectangles[0].Rectangle; // get the page number of target where the TOC entry points int tocEntryTargetPageNumber = tocEntryTargetLocation.PdfRectangles[0].PageIndex + 1; for (int i = 0; i < lstBlankPage.Count; i++) { if (lstBlankPage[i] <= tocEntryTargetPageNumber) { tocEntryTargetPageNumber++; } } // add dashed line from text entry to the page number LineElement lineToNumber = new LineElement(tocEntryPdfRectangle.Right + 5, tocEntryPdfRectangle.Y + tocEntryPdfRectangle.Height / 1.2F, tocEntryMaxRight, tocEntryPdfRectangle.Y + tocEntryPdfRectangle.Height / 1.2F); lineToNumber.LineStyle.LineWidth = 1; lineToNumber.LineStyle.LineDashStyle = LineDashStyle.Dot; lineToNumber.ForeColor = Color.Black; tocEntryPdfPage.AddElement(lineToNumber); // create the page number text element to the right of the TOC entry TextElement pageNumberTextEement = new TextElement(tocEntryMaxRight + 5, tocEntryPdfRectangle.Y, -1, tocEntryPdfRectangle.Height, tocEntryTargetPageNumber.ToString(), pageNumberFont); pageNumberTextEement.TextAlign = HorizontalTextAlign.Left; pageNumberTextEement.VerticalTextAlign = VerticalTextAlign.Middle; pageNumberTextEement.ForeColor = Color.Black; // add the page number to the right of the TOC entry tocEntryPdfPage.AddElement(pageNumberTextEement); } #endregion #region Set Header On Each Pages // the width is given by the PDF page width float altHeaderFooterWidth = pdfDocument.Pages[0].ClientRectangle.Width; float altHeaderHeight = pdfConverter.PdfHeaderOptions.HeaderHeight; //Add Header Chapter for last chapter in Header list for (int pages = lstHeader.Count; pages < pdfDocument.Pages.Count; pages++) { lstHeader.Add(strHeader); } //Remove Unnecessary Header Line from Header Document for (int pageIndex = 0; pageIndex < header.Pages.Count; pageIndex++) { Template tmpHeaderTemplate = pdfDocument.Templates.AddNewTemplate(altHeaderFooterWidth, altHeaderHeight); PdfPage pdfPage = header.Pages[pageIndex]; pdfPage.CustomHeaderTemplate = tmpHeaderTemplate; pdfPage.ShowHeaderTemplate = true; } //Iterate through pages and add header details on each page.. i.e. Chapter Name, Page Number for (int pageIndex = 0; pageIndex < pdfDocument.Pages.Count; pageIndex++) { // create the alternate header template Template altHeaderTemplate = pdfDocument.Templates.AddNewTemplate(altHeaderFooterWidth, altHeaderHeight); TextElement txtHeader = new TextElement(10, altHeaderHeight, lstHeader[pageIndex].ToString(), pageNumberFont, Color.Black); altHeaderTemplate.AddElement(txtHeader); TextElement txtPageNumber = new TextElement(altHeaderFooterWidth - 50, altHeaderHeight, (pageIndex + 1).ToString(), pageNumberFont, Color.Black); altHeaderTemplate.AddElement(txtPageNumber); PdfPage pdfPage = pdfDocument.Pages[pageIndex]; pdfPage.CustomHeaderTemplate = altHeaderTemplate; pdfPage.ShowHeaderTemplate = true; } #endregion mergedDocument.AppendDocument(header); mergedDocument.AppendDocument(pdfDocument); try { mergedDocument.Save(PDFPath); } finally { // close the Documents to realease all the resources mergedDocument.Close(); header.Close(); pdfDocument.Close(); document.Close(); pdfDocumentI.Close(); lstBlankPage.Clear(); TOC_INDEX_COUNT = 0; FreeResources(); } }
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 { string htmlWithLinksAndAttachMarkers = collection["htmlStringTextBox"]; string baseUrl = collection["baseUrlTextBox"]; // Convert a HTML string with markers for file links and attachments to a PDF document object pdfDocument = htmlToPdfConverter.ConvertHtmlToPdfDocumentObject(htmlWithLinksAndAttachMarkers, baseUrl); // Display the attachments panel when the PDF document is opened in a PDF viewer pdfDocument.ViewerPreferences.PageMode = ViewerPageMode.UseAttachments; // Create File Attachments // Create an attachment from a file without icon string fileAttachmentPath = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Attach_Files/Attachment_File.txt"; pdfDocument.AddFileAttachment(fileAttachmentPath, "Attachment from File"); // Create an attachment from a stream without icon string fileStreamAttachmentPath = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Attach_Files/Attachment_Stream.txt"; System.IO.FileStream attachmentStream = new System.IO.FileStream(fileStreamAttachmentPath, System.IO.FileMode.Open, System.IO.FileAccess.Read); pdfDocument.AddFileAttachment(attachmentStream, "Attachment_Stream.txt", "Attachment from Stream"); // Create an attachment from file with paperclip icon in PDF HtmlElementMapping attachFromFileIconMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("attach_from_file_icon"); if (attachFromFileIconMapping != null) { PdfPage attachFromFilePage = attachFromFileIconMapping.PdfRectangles[0].PdfPage; RectangleF attachFromFileIconRectangle = attachFromFileIconMapping.PdfRectangles[0].Rectangle; string fileAttachmentWithIconPath = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Attach_Files/Attachment_File_Icon.txt"; // Create the attachment from file FileAttachmentElement attachFromFileElement = new FileAttachmentElement(attachFromFileIconRectangle, fileAttachmentWithIconPath); attachFromFileElement.IconType = FileAttachmentIcon.Paperclip; attachFromFileElement.Text = "Attachment from File with Paperclip Icon"; attachFromFileElement.IconColor = Color.Blue; attachFromFilePage.AddElement(attachFromFileElement); } // Create an attachment from stream with pushpin icon in PDF System.IO.FileStream attachmentStreamWithIcon = null; HtmlElementMapping attachFromStreamIconMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("attach_from_stream_icon"); if (attachFromStreamIconMapping != null) { PdfPage attachFromStreamPage = attachFromStreamIconMapping.PdfRectangles[0].PdfPage; RectangleF attachFromStreamIconRectangle = attachFromStreamIconMapping.PdfRectangles[0].Rectangle; string fileStreamAttachmentWithIconPath = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Attach_Files/Attachment_Stream_Icon.txt"; attachmentStreamWithIcon = new System.IO.FileStream(fileStreamAttachmentWithIconPath, System.IO.FileMode.Open, System.IO.FileAccess.Read); // Create the attachment from stream FileAttachmentElement attachFromStreamElement = new FileAttachmentElement(attachFromStreamIconRectangle, attachmentStreamWithIcon, "Attachment_Stream_Icon.txt"); attachFromStreamElement.IconType = FileAttachmentIcon.PushPin; attachFromStreamElement.Text = "Attachment from Stream with Pushpin Icon"; attachFromStreamElement.IconColor = Color.Green; attachFromStreamPage.AddElement(attachFromStreamElement); } // 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 = "File_Links_and_Attachments.pdf"; return(fileResult); } finally { // Close the PDF document if (pdfDocument != null) { pdfDocument.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; Document pdfDocument = null; try { string htmlWithLinksAndAttachMarkers = collection["htmlStringTextBox"]; string baseUrl = collection["baseUrlTextBox"]; // Convert a HTML string with markers for file links and attachments to a PDF document object pdfDocument = htmlToPdfConverter.ConvertHtmlToPdfDocumentObject(htmlWithLinksAndAttachMarkers, baseUrl); // Make the HTML element with 'text_note' mapping ID a text note HtmlElementMapping textNoteMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("text_note"); if (textNoteMapping != null) { PdfPage textNotePage = textNoteMapping.PdfRectangles[0].PdfPage; RectangleF textNoteRectangle = textNoteMapping.PdfRectangles[0].Rectangle; // Create the text note TextNoteElement textNoteElement = new TextNoteElement(textNoteRectangle, "This is an initially closed text note"); textNoteElement.NoteIcon = TextNoteIcon.Note; textNoteElement.Open = false; textNotePage.AddElement(textNoteElement); } // Make the HTML element with 'text_note_opened' mapping ID an initially opened text note HtmlElementMapping textNoteOpenedMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("text_note_opened"); if (textNoteOpenedMapping != null) { PdfPage textNoteOpenedPage = textNoteOpenedMapping.PdfRectangles[0].PdfPage; RectangleF textNoteOpenedRectangle = textNoteOpenedMapping.PdfRectangles[0].Rectangle; // Create the text note TextNoteElement textNoteOpenedElement = new TextNoteElement(textNoteOpenedRectangle, "This is an initially opened text note"); textNoteOpenedElement.NoteIcon = TextNoteIcon.Note; textNoteOpenedElement.Open = true; textNoteOpenedPage.AddElement(textNoteOpenedElement); } // Make the HTML element with 'help_note' mapping ID a help note HtmlElementMapping helpNoteMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("help_note"); if (helpNoteMapping != null) { PdfPage helpNotePage = helpNoteMapping.PdfRectangles[0].PdfPage; RectangleF helpNoteRectangle = helpNoteMapping.PdfRectangles[0].Rectangle; // Create the text note TextNoteElement helpNoteElement = new TextNoteElement(helpNoteRectangle, "This is an initially closed help note"); helpNoteElement.NoteIcon = TextNoteIcon.Help; helpNoteElement.Open = false; helpNotePage.AddElement(helpNoteElement); } // Make the HTML element with 'help_note_opened' mapping ID an initially opened help note HtmlElementMapping helpNoteOpenedMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("help_note_opened"); if (helpNoteOpenedMapping != null) { PdfPage helpNoteOpenedPage = helpNoteOpenedMapping.PdfRectangles[0].PdfPage; RectangleF helpNoteOpenedRectangle = helpNoteOpenedMapping.PdfRectangles[0].Rectangle; // Create the text note TextNoteElement helpNoteOpenedElement = new TextNoteElement(helpNoteOpenedRectangle, "This is an initially opened help note"); helpNoteOpenedElement.NoteIcon = TextNoteIcon.Help; helpNoteOpenedElement.Open = true; helpNoteOpenedPage.AddElement(helpNoteOpenedElement); } // Make the HTML element with 'comment_note' mapping ID a comment note HtmlElementMapping commentNoteMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("comment_note"); if (commentNoteMapping != null) { PdfPage commentNotePage = commentNoteMapping.PdfRectangles[0].PdfPage; RectangleF commentNoteRectangle = commentNoteMapping.PdfRectangles[0].Rectangle; // Create the text note TextNoteElement commentNoteElement = new TextNoteElement(commentNoteRectangle, "This is an initially closed comment note"); commentNoteElement.NoteIcon = TextNoteIcon.Comment; commentNoteElement.Open = false; commentNotePage.AddElement(commentNoteElement); } // Make the HTML element with 'comment_note_opened' mapping ID an initially opened comment note HtmlElementMapping commentNoteOpenedMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("comment_note_opened"); if (commentNoteOpenedMapping != null) { PdfPage commentNoteOpenedPage = commentNoteOpenedMapping.PdfRectangles[0].PdfPage; RectangleF commentNoteOpenedRectangle = commentNoteOpenedMapping.PdfRectangles[0].Rectangle; // Create the text note TextNoteElement commentNoteOpenedElement = new TextNoteElement(commentNoteOpenedRectangle, "This is an initially opened comment note"); commentNoteOpenedElement.NoteIcon = TextNoteIcon.Comment; commentNoteOpenedElement.Open = true; commentNoteOpenedPage.AddElement(commentNoteOpenedElement); } // Make the HTML element with 'paragraph_note' mapping ID a paragraph note HtmlElementMapping paragraphNoteMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("paragraph_note"); if (paragraphNoteMapping != null) { PdfPage paragraphNotePage = paragraphNoteMapping.PdfRectangles[0].PdfPage; RectangleF paragraphNoteRectangle = paragraphNoteMapping.PdfRectangles[0].Rectangle; // Create the text note TextNoteElement paragraphNoteElement = new TextNoteElement(paragraphNoteRectangle, "This is an initially closed paragraph note"); paragraphNoteElement.NoteIcon = TextNoteIcon.Paragraph; paragraphNoteElement.Open = false; paragraphNotePage.AddElement(paragraphNoteElement); } // Make the HTML element with 'new_paragraph_note' mapping ID a new paragraph note HtmlElementMapping newParagraphNoteMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("new_paragraph_note"); if (newParagraphNoteMapping != null) { PdfPage newParagraphNotePage = newParagraphNoteMapping.PdfRectangles[0].PdfPage; RectangleF newParagraphNoteRectangle = newParagraphNoteMapping.PdfRectangles[0].Rectangle; // Create the text note TextNoteElement newParagraphNoteElement = new TextNoteElement(newParagraphNoteRectangle, "This is an initially closed new paragraph note"); newParagraphNoteElement.NoteIcon = TextNoteIcon.NewParagraph; newParagraphNoteElement.Open = false; newParagraphNotePage.AddElement(newParagraphNoteElement); } // Make the HTML element with 'key_note' mapping ID a key note HtmlElementMapping keyNoteMapping = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByMappingId("key_note"); if (keyNoteMapping != null) { PdfPage keyNotePage = keyNoteMapping.PdfRectangles[0].PdfPage; RectangleF keyNoteRectangle = keyNoteMapping.PdfRectangles[0].Rectangle; // Create the text note TextNoteElement keyNoteElement = new TextNoteElement(keyNoteRectangle, "This is an initially closed key note"); keyNoteElement.NoteIcon = TextNoteIcon.Key; keyNoteElement.Open = false; keyNotePage.AddElement(keyNoteElement); } // 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 = "Text_Notes.pdf"; return(fileResult); } finally { // Close the PDF document if (pdfDocument != null) { pdfDocument.Close(); } } }
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; // Select all images from HTML page htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors = new string[] { "img" }; // Exclude the original images from rendering becuase they will be replaced by an image from local file system htmlToPdfConverter.HiddenHtmlElementsSelectors = new string[] { "img" }; // Convert a HTML string with images to replace to a PDF document object Document pdfDocument = htmlToPdfConverter.ConvertUrlToPdfDocumentObject(urlTextBox.Text); // Replace the images selected in HTML using special attributes with images from local file system int mappingsCount = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.Count; for (int i = 0; i < mappingsCount; i++) { HtmlElementMapping imageElementInfo = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetByIndex(i); PdfPage imagePdfPage = pdfDocument.GetPage(imageElementInfo.PdfRectangles[0].PageIndex); RectangleFloat imageRectangle = imageElementInfo.PdfRectangles[0].Rectangle; ImageElement newImageElement = new ImageElement(imageRectangle.X, imageRectangle.Y, imageRectangle.Width, imageRectangle.Height, Server.MapPath("~/DemoAppFiles/Input/Images/box.jpg")); newImageElement.EnlargeEnabled = true; imagePdfPage.AddElement(newImageElement); } // 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=Replace_with_Higher_Quality_Images.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; string htmlWithDigitalSignatureMarker = htmlStringTextBox.Text; string baseUrl = baseUrlTextBox.Text; // Convert a HTML string with a marker for digital signature to a PDF document object Document 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 = pdfDocument.GetPage(digitalSignatureMapping.PdfRectangles[0].PageIndex); RectangleFloat digitalSignatureRectangle = digitalSignatureMapping.PdfRectangles[0].Rectangle; string certificateFilePath = Server.MapPath("~/DemoAppFiles/Input/Certificates/evopdf.pfx"); // Create the digital signature DigitalSignatureElement signature = new DigitalSignatureElement(digitalSignatureRectangle, certificateFilePath, "evopdf", 0); 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(); }
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; Document pdfDocument = null; // 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 (convertHtmlRadioButton.Checked) { string htmlWithMappingAttributes = htmlStringTextBox.Text; string baseUrl = baseUrlTextBox.Text; // Convert a HTML string with mapping attributes to a PDF document object pdfDocument = htmlToPdfConverter.ConvertHtmlToPdfDocumentObject(htmlWithMappingAttributes, baseUrl); } else { string url = urlTextBox.Text; // 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(); for (int mappingIndex = 0; mappingIndex < htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.Count; mappingIndex++) { HtmlElementMapping htmlElementInfo = htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetByIndex(mappingIndex); // 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; NameValuePairsCollection htmlElementAttributes = htmlElementInfo.HtmlElementAttributes; PdfRectangle[] 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++) { NameValuePair nameValuePair = htmlElementAttributes.GetByIndex(i); htmlElementInfoBuilder.AppendFormat(" {0} = \"{1}\"<br/>", nameValuePair.Name, nameValuePair.Value); } htmlElementInfoBuilder.AppendFormat("<b>Location in PDF:</b><br/>"); for (int i = 0; i < htmlElementRectanglesInPdf.Length; i++) { PdfPage pdfPage = pdfDocument.GetPage(htmlElementRectanglesInPdf[i].PageIndex); int pdfPageIndex = htmlElementRectanglesInPdf[i].PageIndex; RectangleFloat 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 = pdfDocument.GetPage(htmlToPdfConverter.ConversionSummary.LastPageIndex); RectangleFloat lastPageRectangle = htmlToPdfConverter.ConversionSummary.LastPageRectangle; HtmlToPdfElement htmlElementInfoHtml = new HtmlToPdfElement(0, lastPageRectangle.Y + lastPageRectangle.Height + 1, htmlElementInfoBuilder.ToString(), null); lastPdfPage.AddElement(htmlElementInfoHtml); // 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=Select_in_HTML_Elements_to_Retrieve.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(); }