/// <summary> /// The BeforeRenderPdfPageEvent event handler where a background image is set in each PDF page /// before the main content is rendered /// </summary> /// <param name="eventParams">The event parameter containing the PDF page being rendered</param> void htmlToPdfConverter_BeforeRenderPdfPageEvent(BeforeRenderPdfPageParams eventParams) { if (!addBackgroundImageCheckBox.Checked) { return; } // Get the PDF page being rendered PdfPage pdfPage = eventParams.Page; // Get the PDF page drawable area width and height float pdfPageWidth = pdfPage.ClientRectangle.Width; float pdfPageHeight = pdfPage.ClientRectangle.Height; // The image to be added as background string backgroundImagePath = Server.MapPath("~/DemoAppFiles/Input/Images/background.jpg"); // The image element to add in background ImageElement backgroundImageElement = new ImageElement(0, 0, pdfPageWidth, pdfPageHeight, backgroundImagePath); backgroundImageElement.KeepAspectRatio = true; backgroundImageElement.EnlargeEnabled = true; // Add the background image element to PDF page before the main content is rendered pdfPage.AddElement(backgroundImageElement); }
public ActionResult CreatePdf(IFormCollection collection) { formCollection = 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 PDF page to PDF document PdfPage pdfPage = pdfDocument.AddPage(); try { // Add a default document header AddHeader(pdfDocument, true); // Add a default document footer AddFooter(pdfDocument, true, true); // Create a HTML to PDF element to add to document HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement(0, 0, collection["urlTextBox"]); // Optionally set a delay before conversion to allow asynchonous scripts to finish htmlToPdfElement.ConversionDelay = 2; // Add HTML to PDF element to document pdfPage.AddElement(htmlToPdfElement); // Automatically close the external PDF documents after the final document is saved pdfDocument.AutoCloseAppendedDocs = true; // Insert an external PDF document in the beginning of the final PDF document string pdfFileBefore = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/PDF_Files/Merge_Before_Conversion.pdf"; Document startExternalDocument = new Document(pdfFileBefore); pdfDocument.InsertDocument(0, startExternalDocument, collection["addHeaderFooterInInsertedPdfCheckBox"].Count > 0, collection["showHeaderInFirstPageCheckBox"].Count > 0, collection["showFooterInFirstPageCheckBox"].Count > 0); // Append an external PDF document at the end of the final PDF document string pdfFileAfter = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/PDF_Files/Merge_After_Conversion.pdf"; Document endExternalDocument = new Document(pdfFileAfter); pdfDocument.AppendDocument(endExternalDocument, collection["addHeaderFooterInAppendedPdfCheckBox"].Count > 0, true, true); // 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 = "Header_Footer_in_External_PDF.pdf"; return(fileResult); } finally { // Close the PDF document pdfDocument.Close(); } }
/// <summary> /// The BeforeRenderPdfPageEvent event handler where a background image is set in each PDF page /// before the main content is rendered /// </summary> /// <param name="eventParams">The event parameter containing the PDF page being rendered</param> void htmlToPdfConverter_BeforeRenderPdfPageEvent(BeforeRenderPdfPageParams eventParams) { if (formCollection["addBackgroundImageCheckBox"][0] == null) { return; } // Get the PDF page being rendered PdfPage pdfPage = eventParams.Page; // Get the PDF page drawable area width and height float pdfPageWidth = pdfPage.ClientRectangle.Width; float pdfPageHeight = pdfPage.ClientRectangle.Height; // The image to be added as background string backgroundImagePath = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Images/background.jpg"; // The image element to add in background ImageElement backgroundImageElement = new ImageElement(0, 0, pdfPageWidth, pdfPageHeight, backgroundImagePath); backgroundImageElement.KeepAspectRatio = true; backgroundImageElement.EnlargeEnabled = true; // Add the background image element to PDF page before the main content is rendered pdfPage.AddElement(backgroundImageElement); }
/// <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 { // Create a HTML to PDF element to add to document HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement(collection["urlTextBox"]); // Optionally set a delay before conversion to allow asynchonous scripts to finish htmlToPdfElement.ConversionDelay = 2; // Add the HTML to PDF element to document pdfPage.AddElement(htmlToPdfElement); 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 pdfDocument.OpenAction.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 = "Execute_Acrobat_JavaScript.pdf"; return(fileResult); } finally { // Close the PDF document pdfDocument.Close(); } }
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) { // Get the server IP and port String serverIP = textBoxServerIP.Text; uint serverPort = uint.Parse(textBoxServerPort.Text); // Create a PDF document Document pdfDocument = new Document(serverIP, serverPort); // Set optional service password if (textBoxServicePassword.Text.Length > 0) { pdfDocument.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 pdfDocument.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Add a page to PDF document PdfPage pdfPage = pdfDocument.AddPage(); 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); string certificateFilePath = Server.MapPath(@"~/DemoAppFiles/Input/Certificates/evopdf.pfx"); // Create the digital signature DigitalSignatureElement signature = new DigitalSignatureElement(certificateFilePath, "evopdf", 0); signature.Reason = "Protect the document from unwanted changes"; signature.ContactInfo = "The contact email is [email protected]"; signature.Location = "Development server"; pdfDocument.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(); }
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 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" }; Document pdfDocument = null; try { // Convert a HTML string with images to replace to a PDF document object pdfDocument = htmlToPdfConverter.ConvertUrlToPdfDocumentObject(collection["urlTextBox"]); // Replace the images selected in HTML using special attributes with images from local file system foreach (HtmlElementMapping imageElementInfo in htmlToPdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult) { PdfPage imagePdfPage = imageElementInfo.PdfRectangles[0].PdfPage; RectangleF imageRectangle = imageElementInfo.PdfRectangles[0].Rectangle; ImageElement newImageElement = new ImageElement(imageRectangle.X, imageRectangle.Y, imageRectangle.Width, imageRectangle.Height, m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/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 file to browser FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf"); fileResult.FileDownloadName = "Replace_with_Higher_Quality_Images.pdf"; return(fileResult); } finally { // Close the PDF document if (pdfDocument != null) { pdfDocument.Close(); } } }
public ActionResult CreatePdf(IFormCollection collection) { formCollection = 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 PDF page to PDF document PdfPage pdfPage = pdfDocument.AddPage(); HtmlToPdfElement htmlToPdfElement = null; try { // Add a default document header AddHeader(pdfDocument, true); // Add a default document footer AddFooter(pdfDocument, true, true); // Create a HTML to PDF element to add to document htmlToPdfElement = new HtmlToPdfElement(0, 0, collection["urlTextBox"]); // Optionally set a delay before conversion to allow asynchonous scripts to finish htmlToPdfElement.ConversionDelay = 2; // Install a handler where to change the header and footer in pages generated by the HTML to PDF element htmlToPdfElement.PrepareRenderPdfPageEvent += new PrepareRenderPdfPageDelegate(htmlToPdfElement_PrepareRenderPdfPageEvent); // Add the HTML to PDF element to document // This will raise the PrepareRenderPdfPageEvent event where the header can be changed per page pdfPage.AddElement(htmlToPdfElement); // 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 = "Change_Header_Footer_Per_Page.pdf"; return(fileResult); } finally { // uninstall handler htmlToPdfElement.PrepareRenderPdfPageEvent -= new PrepareRenderPdfPageDelegate(htmlToPdfElement_PrepareRenderPdfPageEvent); // Close the PDF document pdfDocument.Close(); } }
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(); // Set the PDF Viewer Preferences // Set page layout to continuous one column, single page, two column left, two column right pdfDocument.ViewerPreferences.PageLayout = SelectedPageLayout(collection["pageLayoutComboBox"]); // Set page mode to default, display attachments, display thumbnails, display attachments pdfDocument.ViewerPreferences.PageMode = SelectedPageMode(collection["pageModeComboBox"]); // Hide the viewer menu pdfDocument.ViewerPreferences.HideMenuBar = collection["hideMenuBarCheckBox"].Count > 0; // Hide the viewer toolbar pdfDocument.ViewerPreferences.HideToolbar = collection["hideToolbarCheckBox"].Count > 0; // Hide scroll bars and navigation controls pdfDocument.ViewerPreferences.HideWindowUI = collection["hideWindowUICheckBox"].Count > 0; // Display the document title in viewer title bar pdfDocument.ViewerPreferences.DisplayDocTitle = collection["displayDocTitleCheckBox"].Count > 0; try { // Create a HTML to PDF element to add to document HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement(collection["urlTextBox"]); // Optionally set a delay before conversion to allow asynchonous scripts to finish htmlToPdfElement.ConversionDelay = 2; // Add the HTML to PDF element to document pdfPage.AddElement(htmlToPdfElement); // 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 = "Set_PDF_Viewer_Preferences.pdf"; return(fileResult); } finally { // Close the PDF document pdfDocument.Close(); } }
void htmlToPdfConverter_AfterRenderPdfPageEvent(AfterRenderPdfPageParams eventParams) { if (formCollection["addStampCheckBox"][0] == null) { return; } // Get the rendered PDF page PdfPage pdfPage = eventParams.Page; int pageNumber = eventParams.PageNumber; int pageCount = eventParams.PageCount; bool isOddPage = pageNumber % 2 != 0; // Get the PDF document Document pdfDocument = pdfPage.Document; // Get the PDF page drawable area width and height float pdfPageWidth = pdfPage.ClientRectangle.Width; float pdfPageHeight = pdfPage.ClientRectangle.Height; // Create a .NET font Font timesNewRomanFont = new Font("Times New Roman", 50, GraphicsUnit.Point); // Create a PDF font PdfFont pdfFont = pdfDocument.AddFont(timesNewRomanFont, true); // The stamp text string text = String.Format("Stamp on Page {0} of {1}", pageNumber, pageCount); // Measure the text float textWidth = pdfFont.GetTextWidth(text); // Calculate the PDF page diagonal float pdfPageDiagonal = (float)Math.Sqrt(pdfPageWidth * pdfPageWidth + pdfPageHeight * pdfPageHeight); // The text location on PDF page diagonal float xLocation = (pdfPageDiagonal - textWidth) / 2; // Create the stamp as a rotated text element TextElement stampTextElement = new TextElement(xLocation, 0, text, pdfFont); stampTextElement.ForeColor = isOddPage ? Color.Blue : Color.Green; stampTextElement.Rotate((float)(Math.Atan(pdfPageHeight / pdfPageWidth) * (180 / Math.PI))); stampTextElement.Opacity = 75; // Add the stamp to PDF page pdfPage.AddElement(stampTextElement); }
protected void createPdfButton_Click(object sender, EventArgs e) { // Create a PDF 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 PDF page to PDF document PdfPage pdfPage = pdfDocument.AddPage(); string headerHtmlUrl = Server.MapPath("~/DemoAppFiles/Input/HTML_Files/Header_HTML.html"); try { // Add the header to PDF document if (autoResizeHeaderRadioButton.Checked) { // Create the document header with a default height // It will be automatically resized in headerHtml_NavigationCompletedEvent handler pdfDocument.AddHeaderTemplate(50); // Create a HTML element to be added in header HtmlToPdfElement headerHtml = new HtmlToPdfElement(headerHtmlUrl); // Install a handler where to create the document header based on HTML element 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 pdfDocument.Header.AddElement(headerHtml); // Uninstall the handler headerHtml.NavigationCompletedEvent += new NavigationCompletedDelegate(headerHtml_NavigationCompletedEvent); } else { // Create the document header with a fixed height pdfDocument.AddHeaderTemplate(float.Parse(headerHeightTextBox.Text)); // Create a HTML to PDF element to be added in header HtmlToPdfElement headerHtml = new HtmlToPdfElement(headerHtmlUrl); // Set the HTML element to fit the container height headerHtml.FitHeight = true; // Add HTML element to fit the fixed header height pdfDocument.Header.AddElement(headerHtml); } // Draw a line at the header bottom if (drawHeaderLine) { float headerWidth = pdfDocument.Header.Width; float headerHeight = pdfDocument.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 pdfDocument.Header.AddElement(headerLine); } // Create a HTML to PDF element to add to document HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement(urlTextBox.Text); // Optionally set a delay before conversion to allow asynchonous scripts to finish htmlToPdfElement.ConversionDelay = 2; // Add the HTML to PDF element to document pdfPage.AddElement(htmlToPdfElement); // 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=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 pdfDocument.Close(); } }
protected void createPdfButton_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="; // Display the bookmarks panel when the PDF document is opened in a PDF viewer pdfDocument.ViewerPreferences.PageMode = ViewerPageMode.UseOutlines; try { // The titles font used to mark various sections of the PDF document PdfFont titleFont = pdfDocument.AddFont(new Font("Times New Roman", 12, FontStyle.Regular, GraphicsUnit.Point)); // Add a new PDF page to PDF document PdfPage page1 = pdfDocument.AddPage(); TextElement pageText = new TextElement(0, 0, "Page 1. Destination of a Top Bookmark with Fit Width View Mode.", titleFont); page1.AddElement(pageText); // Add a new PDF page to PDF document PdfPage page2 = pdfDocument.AddPage(); pageText = new TextElement(0, 0, "Page 2. Destination of a Top Bookmark with Custom Zoom Level.", titleFont); page2.AddElement(pageText); // Add a new PDF page to PDF document PdfPage page3 = pdfDocument.AddPage(); pageText = new TextElement(0, 0, "Page 3. Destination of a Child Bookmark with Fit Width and Height View Mode.", titleFont); page3.AddElement(pageText); // Add a new PDF page to PDF document PdfPage page4 = pdfDocument.AddPage(); pageText = new TextElement(0, page4.PageSize.Height / 2 - 20, "Page 4. Destination of a Top Bookmark for the Middle of the Page.", titleFont); page4.AddElement(pageText); // Add a new PDF page to PDF document PdfPage page5 = pdfDocument.AddPage(); pageText = new TextElement(0, 0, "Page 5. Destination of a Child Bookmark with Colored Title.", titleFont); page5.AddElement(pageText); // Add a new PDF page to PDF document PdfPage page6 = pdfDocument.AddPage(); pageText = new TextElement(0, 0, "Page 6. Destination of a Child Bookmark with Italic Style Title.", titleFont); page6.AddElement(pageText); // Add a top level bookmark for first page setting destination view mode to fit viewer window horizontally ExplicitDestination page1Destination = new ExplicitDestination(page1, new PointF(0, 0), DestinationViewMode.FitH); Bookmark page1TopBookmark = pdfDocument.Bookmarks.AddNewBookmark("Top Bookmark with Fit Width View Mode", page1Destination); page1TopBookmark.Style = PdfBookmarkStyle.Bold; // Add a top level bookmark for second page setting the zoom level to 125% ExplicitDestination page2Destination = new ExplicitDestination(page2, new PointF(0, 0), DestinationViewMode.XYZ); page2Destination.ZoomPercentage = 125; Bookmark page2TopBookmark = pdfDocument.Bookmarks.AddNewBookmark("Top Bookmark with Custom Zoom Level", page2Destination); page2TopBookmark.Style = PdfBookmarkStyle.Normal; // Add a child bookmark for third page setting destination view mode to fit viewer window horizontally and vertically ExplicitDestination page3Destination = new ExplicitDestination(page3, new PointF(0, 0), DestinationViewMode.Fit); Bookmark page3ChildBookmark = page2TopBookmark.DescendantBookmarks.AddNewBookmark("Child Bookmark with Fit Width and Height View Mode", page3Destination); // Add a top level bookmark for fourth page with destination point in the middle of the PDF page ExplicitDestination page4Destination = new ExplicitDestination(page4, new PointF(0, page4.PageSize.Height / 2 - 20)); Bookmark page4TopBookmark = pdfDocument.Bookmarks.AddNewBookmark("Top Bookmark for the Middle of the Page", page4Destination); page4TopBookmark.Style = PdfBookmarkStyle.Bold; page4TopBookmark.Color = Color.Blue; // Add a child bookmark with colored text ExplicitDestination page5Destination = new ExplicitDestination(page5, new PointF(0, 0)); Bookmark page5ChildBookmark = page4TopBookmark.DescendantBookmarks.AddNewBookmark("Child Bookmark with Colored Title", page5Destination); page5ChildBookmark.Color = Color.Red; // Add a child bookmark with italic style text ExplicitDestination page6Destination = new ExplicitDestination(page6, new PointF(0, 0)); Bookmark page6ChildBookmark = page4TopBookmark.DescendantBookmarks.AddNewBookmark("Child Bookmark with Italic Colored Title", page6Destination); page6ChildBookmark.Style = PdfBookmarkStyle.Italic; page6ChildBookmark.Color = Color.Green; // 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=Bookmarks.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(); } }
public ActionResult ConvertHtmlToPdf(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="; // Create a PDF page where to add the first HTML PdfPage firstPdfPage = pdfDocument.AddPage(); try { // The image location in PDF float xLocation = float.Parse(collection["xLocationTextBox"]); float yLocation = float.Parse(collection["yLocationTextBox"]); // The URL of the HTML page to convert to an image in PDF string urlToConvert = collection["urlTextBox"]; // Create the HTML to Image element HtmlToImageElement htmlToImageElement = new HtmlToImageElement(xLocation, yLocation, urlToConvert); // Optionally set the HTML viewer width htmlToImageElement.HtmlViewerWidth = int.Parse(collection["htmlViewerWidthTextBox"]); // Optionally set the HTML viewer height if (collection["htmlViewerHeightTextBox"][0].Length > 0) { htmlToImageElement.HtmlViewerHeight = int.Parse(collection["htmlViewerHeightTextBox"]); } // Optionally set the HTML content clipping option to force the HTML content width to be exactly HtmlViewerWidth pixels htmlToImageElement.ClipHtmlView = collection["clipContentCheckBox"].Count > 0; // Optionally set the destination width in PDF if (collection["contentWidthTextBox"][0].Length > 0) { htmlToImageElement.Width = float.Parse(collection["contentWidthTextBox"]); } // Optionally set the destination height in PDF if (collection["contentHeightTextBox"][0].Length > 0) { htmlToImageElement.Height = float.Parse(collection["contentHeightTextBox"]); } // Optionally set a delay before conversion to allow asynchonous scripts to finish htmlToImageElement.ConversionDelay = 2; // Add the HTML to Image element to PDF document // The AddElementResult contains the bounds of the HTML to Image Element in last rendered PDF page // such that you can start a new PDF element right under it AddElementResult result = firstPdfPage.AddElement(htmlToImageElement); // 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 = "Add_HTML_to_Image_Elements_to_PDF.pdf"; return(fileResult); } finally { // Close the PDF document pdfDocument.Close(); } }
protected void convertToPdfButton_Click(object sender, EventArgs e) { // Create the PDF document where to add the HTML documents 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="; // Create a PDF page where to add the first HTML PdfPage firstPdfPage = pdfDocument.AddPage(); try { // Create the first HTML to PDF element HtmlToPdfElement firstHtml = new HtmlToPdfElement(0, 0, firstUrlTextBox.Text); // Optionally set a delay before conversion to allow asynchonous scripts to finish firstHtml.ConversionDelay = 2; // Add the first HTML to PDF document AddElementResult firstAddResult = firstPdfPage.AddElement(firstHtml); PdfPage secondPdfPage = null; PointF secondHtmlLocation = Point.Empty; if (startNewPageCheckBox.Checked) { // Create a PDF page where to add the second HTML secondPdfPage = pdfDocument.AddPage(); secondHtmlLocation = PointF.Empty; } else { // Add the second HTML on the PDF page where the first HTML ended secondPdfPage = firstAddResult.EndPdfPage; secondHtmlLocation = new PointF(firstAddResult.EndPageBounds.Left, firstAddResult.EndPageBounds.Bottom); } // Create the second HTML to PDF element HtmlToPdfElement secondHtml = new HtmlToPdfElement(secondHtmlLocation.X, secondHtmlLocation.Y, secondUrlTextBox.Text); // Optionally set a delay before conversion to allow asynchonous scripts to finish secondHtml.ConversionDelay = 2; // Add the second HTML to PDF document secondPdfPage.AddElement(secondHtml); // 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=Merge_Multipe_HTML.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 createPdfButton_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 PDF page to PDF document PdfPage pdfPage = pdfDocument.AddPage(); try { // Add a default document header AddHeader(pdfDocument, true); // Add a default document footer AddFooter(pdfDocument, true, true); // Create a HTML to PDF element to add to document HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement(0, 0, urlTextBox.Text); // Optionally set a delay before conversion to allow asynchonous scripts to finish htmlToPdfElement.ConversionDelay = 2; // Add HTML to PDF element to document pdfPage.AddElement(htmlToPdfElement); // Automatically close the external PDF documents after the final document is saved pdfDocument.AutoCloseAppendedDocs = true; // Insert an external PDF document in the beginning of the final PDF document string pdfFileBefore = Server.MapPath("~/DemoAppFiles/Input/PDF_Files/Merge_Before_Conversion.pdf"); Document startExternalDocument = new Document(pdfFileBefore); pdfDocument.InsertDocument(0, startExternalDocument, addHeaderFooterInInsertedPdfCheckBox.Checked, showHeaderInFirstPageCheckBox.Checked, showFooterInFirstPageCheckBox.Checked); // Append an external PDF document at the end of the final PDF document string pdfFileAfter = Server.MapPath("~/DemoAppFiles/Input/PDF_Files/Merge_After_Conversion.pdf"); Document endExternalDocument = new Document(pdfFileAfter); pdfDocument.AppendDocument(endExternalDocument, addHeaderFooterInAppendedPdfCheckBox.Checked, true, true); // 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=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(); } finally { // Close the PDF document pdfDocument.Close(); } }
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="; try { // The result of adding Text Elements to PDF document AddElementResult addTextResult = null; // The titles font used to mark various sections of the PDF document PdfFont titleFont = pdfDocument.AddFont(new Font("Times New Roman", 10, FontStyle.Bold, GraphicsUnit.Point)); titleFont.IsUnderline = true; // The position on X anf Y axes where to add the next element float yLocation = 5; float xLocation = 5; // Create a PDF page in PDF document PdfPage pdfPage = pdfDocument.AddPage(); // Text Elements Using Fonts Installed in System // Add section title TextElement titleTextElement = new TextElement(xLocation, yLocation, "Text Elements Using Fonts Installed in System", titleFont); titleTextElement.ForeColor = Color.DarkGreen; addTextResult = pdfPage.AddElement(titleTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 10; xLocation += 5; pdfPage = addTextResult.EndPdfPage; // Embed in PDF document a font with Normal style installed in system Font systemFontNormal = new Font("Times New Roman", 10, GraphicsUnit.Point); PdfFont embeddedSystemFontNormal = pdfDocument.AddFont(systemFontNormal); // Add a text element using a font with Normal style installed in system TextElement embeddedSystemFontNormalTextElement = new TextElement(xLocation, yLocation, "This text uses a font with Normal style installed in system", embeddedSystemFontNormal); addTextResult = pdfPage.AddElement(embeddedSystemFontNormalTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Embed in PDF document a font with Bold style installed in system Font systemFontBold = new Font("Times New Roman", 10, FontStyle.Bold, GraphicsUnit.Point); PdfFont embeddedSystemFontBold = pdfDocument.AddFont(systemFontBold); // Add a text element using a font with Bold style installed in system TextElement embeddedSystemFontBoldTextElement = new TextElement(xLocation, yLocation, "This text uses a font with Bold style installed in system", embeddedSystemFontBold); addTextResult = pdfPage.AddElement(embeddedSystemFontBoldTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Embed in PDF document a font with Italic style installed in system Font systemFontItalic = new Font("Times New Roman", 10, FontStyle.Italic, GraphicsUnit.Point); PdfFont embeddedSystemFontItalic = pdfDocument.AddFont(systemFontItalic); // Add a text element using a font with Italic style installed in system TextElement embeddedSystemFontItalicTextElement = new TextElement(xLocation, yLocation, "This text uses a font with Italic style installed in system", embeddedSystemFontItalic); addTextResult = pdfPage.AddElement(embeddedSystemFontItalicTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Text Elements Using Fonts From Local Files // Add section title xLocation -= 5; yLocation += 10; titleTextElement = new TextElement(xLocation, yLocation, "Text Elements Using Fonts From Local Files", titleFont); titleTextElement.ForeColor = Color.Navy; addTextResult = pdfPage.AddElement(titleTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 10; xLocation += 5; pdfPage = addTextResult.EndPdfPage; // Embed a True Type font from a local file in PDF document PdfFont localTrueTypeFont = pdfDocument.AddFont(m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Fonts/TrueType.ttf"); // Add a text element using the local True Type font to PDF document TextElement localFontTtfTextElement = new TextElement(xLocation, yLocation, "This text uses a True Type Font loaded from a local file", localTrueTypeFont); addTextResult = pdfPage.AddElement(localFontTtfTextElement); yLocation = addTextResult.EndPageBounds.Bottom; pdfPage = addTextResult.EndPdfPage; // Embed an OpenType font with TrueType Outlines in PDF document PdfFont localOpenTypeTrueTypeFont = pdfDocument.AddFont(m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Fonts/OpenTypeTrueType.otf"); // Add a text element using the local OpenType font with TrueType Outlines to PDF document TextElement localOpenTypeTrueTypeFontTextElement = new TextElement(xLocation, yLocation, "This text uses an Open Type Font with TrueType Outlines loaded from a local file", localOpenTypeTrueTypeFont); addTextResult = pdfPage.AddElement(localOpenTypeTrueTypeFontTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Embed an OpenType font with PostScript Outlines in PDF document PdfFont localOpenTypePostScriptFont = pdfDocument.AddFont(m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Fonts/OpenTypePostScript.otf"); // Add a text element using the local OpenType font with PostScript Outlines to PDF document TextElement localOpenTypePostScriptFontTextElement = new TextElement(xLocation, yLocation, "This text uses an Open Type Font with PostScript Outlines loaded from a local file", localOpenTypePostScriptFont); addTextResult = pdfPage.AddElement(localOpenTypePostScriptFontTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Text Elements Using Standard PDF Fonts // Add section title xLocation -= 5; yLocation += 10; titleTextElement = new TextElement(xLocation, yLocation, "Text Elements Using Standard PDF Fonts", titleFont); titleTextElement.ForeColor = Color.DarkGreen; addTextResult = pdfPage.AddElement(titleTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 10; xLocation += 5; pdfPage = addTextResult.EndPdfPage; // Create a standard PDF font with Normal style PdfFont standardPdfFontNormal = pdfDocument.AddFont(StdFontBaseFamily.Helvetica); standardPdfFontNormal.Size = 10; // Add a text element using the standard PDF font with Normal style TextElement standardPdfFontNormalTextElement = new TextElement(xLocation, yLocation, "This text uses a standard PDF font with Normal style", standardPdfFontNormal); addTextResult = pdfPage.AddElement(standardPdfFontNormalTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Create a standard PDF font with Bold style PdfFont standardPdfFontBold = pdfDocument.AddFont(StdFontBaseFamily.HelveticaBold); standardPdfFontBold.Size = 10; // Add a text element using the standard PDF font with Bold style TextElement standardPdfFontBoldTextElement = new TextElement(xLocation, yLocation, "This text uses a standard PDF font with Bold style", standardPdfFontBold); addTextResult = pdfPage.AddElement(standardPdfFontBoldTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Create a standard PDF font with Italic style PdfFont standardPdfFontItalic = pdfDocument.AddFont(StdFontBaseFamily.HelveticaOblique); standardPdfFontItalic.Size = 10; // Add a text element using the standard PDF font with Italic style TextElement standardPdfFontItalicTextElement = new TextElement(xLocation, yLocation, "This text uses a standard PDF font with Italic style", standardPdfFontItalic); addTextResult = pdfPage.AddElement(standardPdfFontItalicTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Text Elements with Vertical Text // Add section title xLocation -= 5; yLocation += 10; titleTextElement = new TextElement(xLocation, yLocation, "Vertical Text", titleFont); titleTextElement.ForeColor = Color.Navy; addTextResult = pdfPage.AddElement(titleTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 10; xLocation += 5; pdfPage = addTextResult.EndPdfPage; // Add a top to bottom vertical text string topBottomText = "This is a Top to Bottom Vertical Text"; float topBottomTextWidth = embeddedSystemFontNormal.GetTextWidth(topBottomText); TextElement topBottomVerticalTextElement = new TextElement(0, 0, topBottomText, embeddedSystemFontNormal); topBottomVerticalTextElement.Translate(xLocation + 25, yLocation); topBottomVerticalTextElement.Rotate(90); pdfPage.AddElement(topBottomVerticalTextElement); // Add a bottom to top vertical text string bottomTopText = "This is a Bottom to Top Vertical Text"; float bottomTopTextWidth = embeddedSystemFontNormal.GetTextWidth(bottomTopText); TextElement bottomTopVerticalTextElement = new TextElement(0, 0, bottomTopText, embeddedSystemFontNormal); bottomTopVerticalTextElement.Translate(xLocation + 125, yLocation + bottomTopTextWidth); bottomTopVerticalTextElement.Rotate(-90); pdfPage.AddElement(bottomTopVerticalTextElement); yLocation += bottomTopTextWidth + 10; // Add a text element that flows freely in width and height string text = System.IO.File.ReadAllText(m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Text_Files/Text_File.txt"); // Add section title xLocation -= 5; yLocation += 10; titleTextElement = new TextElement(xLocation, yLocation, "Text Element that flows freely in width and height", titleFont); titleTextElement.ForeColor = Color.DarkGreen; addTextResult = pdfPage.AddElement(titleTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 10; xLocation += 5; pdfPage = addTextResult.EndPdfPage; // Add the text element TextElement freeWidthAndHeightTextElement = new TextElement(xLocation, yLocation, text, embeddedSystemFontNormal); addTextResult = pdfPage.AddElement(freeWidthAndHeightTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Add a text element with a given width that flows freely in height // Add section title xLocation -= 5; yLocation += 10; titleTextElement = new TextElement(xLocation, yLocation, "Text Element with a given width that flows freely in height", titleFont); titleTextElement.ForeColor = Color.Navy; addTextResult = pdfPage.AddElement(titleTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 10; xLocation += 5; pdfPage = addTextResult.EndPdfPage; // Add the text element TextElement freeHeightTextElement = new TextElement(xLocation, yLocation, 400, text, embeddedSystemFontNormal); addTextResult = pdfPage.AddElement(freeHeightTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Add a bounding rectangle for text element RectangleElement border = new RectangleElement(addTextResult.EndPageBounds.X, addTextResult.EndPageBounds.Y, addTextResult.EndPageBounds.Width, addTextResult.EndPageBounds.Height); pdfPage.AddElement(border); // Add a text element with a given width and height // Add section title xLocation -= 5; yLocation += 10; titleTextElement = new TextElement(xLocation, yLocation, "Text Element with a given width and height", titleFont); titleTextElement.ForeColor = Color.DarkGreen; addTextResult = pdfPage.AddElement(titleTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 10; xLocation += 5; pdfPage = addTextResult.EndPdfPage; // Add the text element TextElement boundedTextElement = new TextElement(xLocation, yLocation, 400, 50, text, embeddedSystemFontNormal); addTextResult = pdfPage.AddElement(boundedTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Add a bounding rectangle for text element border = new RectangleElement(addTextResult.EndPageBounds.X, addTextResult.EndPageBounds.Y, addTextResult.EndPageBounds.Width, addTextResult.EndPageBounds.Height); pdfPage.AddElement(border); // Add a text element that flows freely on next PDF page // Add section title xLocation -= 5; yLocation += 10; titleTextElement = new TextElement(xLocation, yLocation, "Text Element that flows freely on multiple PDF pages", titleFont); titleTextElement.ForeColor = Color.Navy; addTextResult = pdfPage.AddElement(titleTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 10; xLocation += 5; pdfPage = addTextResult.EndPdfPage; // Add the text element string multiPageText = System.IO.File.ReadAllText(m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Text_Files/Large_Text_File.txt"); TextElement multiPageTextElement = new TextElement(xLocation, yLocation, 575, multiPageText, embeddedSystemFontNormal); multiPageTextElement.BackColor = Color.WhiteSmoke; addTextResult = pdfPage.AddElement(multiPageTextElement); yLocation = addTextResult.EndPageBounds.Bottom + 3; pdfPage = addTextResult.EndPdfPage; // Add a line at the bottom of the multipage text element LineElement bottomLine = new LineElement(addTextResult.EndPageBounds.X, addTextResult.EndPageBounds.Bottom + 1, addTextResult.EndPageBounds.X + addTextResult.EndPageBounds.Width, addTextResult.EndPageBounds.Bottom + 1); pdfPage.AddElement(bottomLine); // Add a text stamp to a PDF document // Create a .NET font Font timesNewRomanFont = new Font("Times New Roman", 24, GraphicsUnit.Point); // Create a PDF font PdfFont stampPdfFont = pdfDocument.AddFont(timesNewRomanFont, true); // The stamp text string stampText = String.Format("Text Stamp {0}", DateTime.Now.ToString("d")); // Measure the text float textWidth = stampPdfFont.GetTextWidth(stampText); foreach (PdfPage page in pdfDocument.Pages) { // Get the PDF page drawable area width and height float pdfPageWidth = page.ClientRectangle.Width; float pdfPageHeight = page.ClientRectangle.Height; // Calculate the PDF page diagonal float pdfPageDiagonal = (float)Math.Sqrt(pdfPageWidth * pdfPageWidth + pdfPageHeight * pdfPageHeight); // The text location on PDF page diagonal float xStampLocation = (pdfPageDiagonal - textWidth) / 2; // Create the stamp as a rotated text element TextElement stampTextElement = new TextElement(xStampLocation, 0, stampText, stampPdfFont); stampTextElement.ForeColor = Color.Coral; stampTextElement.Rotate((float)(Math.Atan(pdfPageHeight / pdfPageWidth) * (180 / Math.PI))); stampTextElement.Opacity = 75; // Add the stamp to PDF page page.AddElement(stampTextElement); } // 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_Elements.pdf"; return(fileResult); } 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 PDF document Document pdfDocument = new Document(serverIP, serverPort); // Set optional service password if (textBoxServicePassword.Text.Length > 0) { pdfDocument.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 pdfDocument.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Create a PDF page where to add the first HTML PdfPage firstPdfPage = pdfDocument.AddPage(); // The element location in PDF float xLocation = float.Parse(xLocationTextBox.Text); float yLocation = float.Parse(yLocationTextBox.Text); // The URL of the HTML page to convert to PDF string urlToConvert = urlTextBox.Text; // Create the HTML to PDF element HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement(xLocation, yLocation, urlToConvert); // Optionally set the HTML viewer width htmlToPdfElement.HtmlViewerWidth = int.Parse(htmlViewerWidthTextBox.Text); // Optionally set the HTML viewer height if (htmlViewerHeightTextBox.Text.Length > 0) { htmlToPdfElement.HtmlViewerHeight = int.Parse(htmlViewerHeightTextBox.Text); } // Optionally set the HTML content clipping option to force the HTML content width to be exactly HtmlViewerWidth pixels htmlToPdfElement.ClipHtmlView = clipContentCheckBox.Checked; // Optionally set the destination width in PDF if (contentWidthTextBox.Text.Length > 0) { htmlToPdfElement.Width = float.Parse(contentWidthTextBox.Text); } // Optionally set the destination height in PDF if (contentHeightTextBox.Text.Length > 0) { htmlToPdfElement.Height = float.Parse(contentHeightTextBox.Text); } // Optionally set a delay before conversion to allow asynchonous scripts to finish htmlToPdfElement.ConversionDelay = 2; // Add the HTML to PDF element to PDF document // The AddElementResult contains the bounds of the HTML to PDF Element in last rendered PDF page // such that you can start a new PDF element right under it firstPdfPage.AddElement(htmlToPdfElement); // 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=HTML_to_PDF_Elements.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(); }
/// <summary> /// Adds the chapter title page. /// </summary> /// <param name="docPDF">The doc PDF.</param> /// <param name="ChapterTitle">The chapter title.</param> internal void AddChapterTitlePage(Document docPDF, String ChapterTitle) { pdfPage = docPDF.AddPage(new Margins(40)); #region Chapter Title /// Generate Text /// Create a Times New Roman Bold .NET font of 10 points System.Drawing.Font ttfFontBold = new System.Drawing.Font("Verdana", 40, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); /// Create the PDF fonts based on the .NET true type fonts PdfFont newVerdanaFontBold = docPDF.AddFont(ttfFontBold); /// Add Title elements to the document TextElement TypeTitle = new TextElement(3, 300, ChapterTitle, newVerdanaFontBold); TypeTitle.TextAlign = HorizontalTextAlign.Center; pdfPage.AddElement(TypeTitle); #endregion }
/// <summary> /// Adds the HTM lto PDF. /// </summary> /// <param name="docPDF">The doc PDF.</param> /// <param name="strBTOC">The STR BTOC.</param> internal void AddHTMLtoPDF(Document docPDF, String strBTOC, string strContext, bool blnIsTOC) { if (blnIsTOC) { strbaseURL = strContext; htmlToPdfElement = new HtmlToPdfElement(Convert.ToString(strBTOC), strbaseURL); pdfPage = docPDF.InsertPage(1, PageSize.A4, new Margins(40), PageOrientation.Portrait); //docPDF.AddPage(PageSize.A4, new Margins(10, 10, 0, 0), PageOrientation.Portrait); pdfPage.AddElement(htmlToPdfElement); docPDF.Pages.Add(pdfPage); } else { strbaseURL = strContext; htmlToPdfElement = new HtmlToPdfElement(Convert.ToString(strBTOC), strbaseURL); pdfPage = docPDF.AddPage(PageSize.A4, new Margins(40), PageOrientation.Portrait); pdfPage.AddElement(htmlToPdfElement); docPDF.Pages.Add(pdfPage); } }
protected void createPdfButton_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="; try { // The result of adding elements to PDF document AddElementResult addElementResult = null; // The titles font used to mark various sections of the PDF document PdfFont titleFont = pdfDocument.AddFont(new Font("Times New Roman", 12, FontStyle.Bold, GraphicsUnit.Point)); PdfFont subtitleFont = pdfDocument.AddFont(new Font("Times New Roman", 8, FontStyle.Bold, GraphicsUnit.Point)); // The position on X anf Y axes where to add the next element float yLocation = 5; float xLocation = 5; // Create a PDF page in PDF document PdfPage pdfPage = pdfDocument.AddPage(); // Add section title TextElement titleTextElement = new TextElement(xLocation, yLocation, "Images Scaling", titleFont); titleTextElement.ForeColor = Color.Black; addElementResult = pdfPage.AddElement(titleTextElement); yLocation = addElementResult.EndPageBounds.Bottom + 10; pdfPage = addElementResult.EndPdfPage; float titlesYLocation = yLocation; // Add an unscaled image // Add section title TextElement subtitleTextElement = new TextElement(xLocation, titlesYLocation, "Unscaled small image with normal resolution", subtitleFont); subtitleTextElement.ForeColor = Color.Navy; addElementResult = pdfPage.AddElement(subtitleTextElement); pdfPage = addElementResult.EndPdfPage; float imagesYLocation = addElementResult.EndPageBounds.Bottom + 10; string imagePath = Server.MapPath("~/DemoAppFiles/Input/Images/picture_small.jpg"); ImageElement unscaledImageElement = new ImageElement(xLocation, imagesYLocation, imagePath); addElementResult = pdfPage.AddElement(unscaledImageElement); RectangleF scaledDownImageRectangle = new RectangleF(addElementResult.EndPageBounds.Right + 30, addElementResult.EndPageBounds.Y, addElementResult.EndPageBounds.Width, addElementResult.EndPageBounds.Height); // Add a large image scaled down to same size in PDF // Add section title subtitleTextElement = new TextElement(scaledDownImageRectangle.X, titlesYLocation, "Scaled down large image has higher resolution", subtitleFont); subtitleTextElement.ForeColor = Color.Navy; pdfPage.AddElement(subtitleTextElement); imagePath = Server.MapPath("~/DemoAppFiles/Input/Images/picture_large.jpg"); ImageElement scaledDownImageElement = new ImageElement(scaledDownImageRectangle.X, scaledDownImageRectangle.Y, scaledDownImageRectangle.Width, imagePath); AddElementResult scaledDownImageResult = pdfPage.AddElement(scaledDownImageElement); // Add a border around the scaled down image RectangleElement borderElement = new RectangleElement(scaledDownImageRectangle); pdfPage.AddElement(borderElement); // Add an unscaled small image float columnX = scaledDownImageResult.EndPageBounds.Right + 30; // Add section title subtitleTextElement = new TextElement(columnX, titlesYLocation, "Unscaled small image", subtitleFont); subtitleTextElement.ForeColor = Color.Navy; pdfPage.AddElement(subtitleTextElement); imagePath = Server.MapPath("~/DemoAppFiles/Input/Images/picture_smaller.jpg"); unscaledImageElement = new ImageElement(columnX, imagesYLocation, imagePath); AddElementResult unscaledImageResult = pdfPage.AddElement(unscaledImageElement); RectangleF unscaledImageRectangle = unscaledImageResult.EndPageBounds; // Add an enlarged image // Add section title subtitleTextElement = new TextElement(columnX, unscaledImageRectangle.Bottom + 10, "Enlarged small image has lower resolution", subtitleFont); subtitleTextElement.ForeColor = Color.Navy; AddElementResult enlargedImageTitle = pdfPage.AddElement(subtitleTextElement); float enlargedImageWidth = unscaledImageRectangle.Width + 35; imagePath = Server.MapPath("~/DemoAppFiles/Input/Images/picture_smaller.jpg"); ImageElement enlargedImageElement = new ImageElement(columnX, enlargedImageTitle.EndPageBounds.Bottom + 10, enlargedImageWidth, imagePath); // Allow the image to be enlarged enlargedImageElement.EnlargeEnabled = true; AddElementResult enalargedImageResult = pdfPage.AddElement(enlargedImageElement); yLocation = addElementResult.EndPageBounds.Bottom + 10; // Scale an image preserving the aspect ratio titlesYLocation = yLocation; // Add section title subtitleTextElement = new TextElement(xLocation, titlesYLocation, "Scaled down image preserving aspect ratio", subtitleFont); subtitleTextElement.ForeColor = Color.Navy; addElementResult = pdfPage.AddElement(subtitleTextElement); pdfPage = addElementResult.EndPdfPage; yLocation = addElementResult.EndPageBounds.Bottom + 10; RectangleF boundingRectangle = new RectangleF(xLocation, yLocation, scaledDownImageRectangle.Width, scaledDownImageRectangle.Width); imagesYLocation = boundingRectangle.Y; imagePath = Server.MapPath("~/DemoAppFiles/Input/Images/landscape.jpg"); ImageElement keepAspectImageElement = new ImageElement(boundingRectangle.X, imagesYLocation, boundingRectangle.Width, boundingRectangle.Width, true, imagePath); addElementResult = pdfPage.AddElement(keepAspectImageElement); borderElement = new RectangleElement(boundingRectangle); borderElement.ForeColor = Color.Black; pdfPage.AddElement(borderElement); // Scale an image without preserving aspect ratio // This can produce a distorted image boundingRectangle = new RectangleF(addElementResult.EndPageBounds.Right + 30, addElementResult.EndPageBounds.Y, scaledDownImageRectangle.Width, scaledDownImageRectangle.Width); // Add section title subtitleTextElement = new TextElement(boundingRectangle.X, titlesYLocation, "Scaled down image without preserving aspect ratio", subtitleFont); subtitleTextElement.ForeColor = Color.Navy; pdfPage.AddElement(subtitleTextElement); imagePath = Server.MapPath("~/DemoAppFiles/Input/Images/landscape.jpg"); ImageElement notKeepAspectImageElement = new ImageElement(boundingRectangle.X, imagesYLocation, boundingRectangle.Width, boundingRectangle.Width, false, imagePath); addElementResult = pdfPage.AddElement(notKeepAspectImageElement); borderElement = new RectangleElement(boundingRectangle); borderElement.ForeColor = Color.Black; pdfPage.AddElement(borderElement); pdfPage = addElementResult.EndPdfPage; yLocation = addElementResult.EndPageBounds.Bottom + 20; // Add transparent images // Add section title titleTextElement = new TextElement(xLocation, yLocation, "Transparent Images", titleFont); titleTextElement.ForeColor = Color.Black; addElementResult = pdfPage.AddElement(titleTextElement); yLocation = addElementResult.EndPageBounds.Bottom + 10; pdfPage = addElementResult.EndPdfPage; imagePath = Server.MapPath("~/DemoAppFiles/Input/Images/transparent.png"); ImageElement trasparentImageElement = new ImageElement(xLocation, yLocation, 150, imagePath); addElementResult = pdfPage.AddElement(trasparentImageElement); imagePath = Server.MapPath("~/DemoAppFiles/Input/Images/rose.png"); trasparentImageElement = new ImageElement(addElementResult.EndPageBounds.Right + 60, yLocation + 20, 150, imagePath); pdfPage.AddElement(trasparentImageElement); pdfPage = addElementResult.EndPdfPage; yLocation = addElementResult.EndPageBounds.Bottom + 20; // Rotate images // Add section title titleTextElement = new TextElement(xLocation, yLocation, "Rotated Images", titleFont); titleTextElement.ForeColor = Color.Black; addElementResult = pdfPage.AddElement(titleTextElement); yLocation = addElementResult.EndPageBounds.Bottom + 10; pdfPage = addElementResult.EndPdfPage; // Add a not rotated image imagePath = Server.MapPath("~/DemoAppFiles/Input/Images/compass.png"); ImageElement noRotationImageElement = new ImageElement(xLocation, yLocation, 125, imagePath); addElementResult = pdfPage.AddElement(noRotationImageElement); float imageXLocation = addElementResult.EndPageBounds.X; float imageYLocation = addElementResult.EndPageBounds.Y; float imageWidth = addElementResult.EndPageBounds.Width; float imageHeight = addElementResult.EndPageBounds.Height; // The rotated coordinates system location float rotatedImageXLocation = imageXLocation + imageWidth + 20 + imageHeight; float rotatedImageYLocation = imageYLocation; // Add the image rotated 90 degrees ImageElement rotate90ImageElement = new ImageElement(0, 0, 125, imagePath); rotate90ImageElement.Translate(rotatedImageXLocation, rotatedImageYLocation); rotate90ImageElement.Rotate(90); pdfPage.AddElement(rotate90ImageElement); rotatedImageXLocation += 20 + imageWidth; rotatedImageYLocation = imageYLocation + imageHeight; // Add the image rotated 180 degrees ImageElement rotate180ImageElement = new ImageElement(0, 0, 125, imagePath); rotate180ImageElement.Translate(rotatedImageXLocation, rotatedImageYLocation); rotate180ImageElement.Rotate(180); pdfPage.AddElement(rotate180ImageElement); rotatedImageXLocation += 20; rotatedImageYLocation = imageYLocation + imageWidth; // Add the image rotated 270 degrees ImageElement rotate270ImageElement = new ImageElement(0, 0, 125, imagePath); rotate270ImageElement.Translate(rotatedImageXLocation, rotatedImageYLocation); rotate270ImageElement.Rotate(270); pdfPage.AddElement(rotate270ImageElement); pdfPage = addElementResult.EndPdfPage; yLocation = addElementResult.EndPageBounds.Bottom + 20; // 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=Image_Elements.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(); } }
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(); // Add second page to PDF document PdfPage secondPdfPage = pdfDocument.AddPage(); // Add third page to PDF document PdfPage thirdPdfPage = pdfDocument.AddPage(); try { // The titles font used to mark various sections of the PDF document PdfFont titleFont = pdfDocument.AddFont(new Font("Times New Roman", 10, FontStyle.Bold, GraphicsUnit.Point)); PdfFont subtitleFont = pdfDocument.AddFont(new Font("Times New Roman", 8, FontStyle.Regular, GraphicsUnit.Point)); // The links text font PdfFont linkTextFont = pdfDocument.AddFont(new Font("Times New Roman", 8, FontStyle.Bold, GraphicsUnit.Point)); linkTextFont.IsUnderline = true; float xLocation = 5; float yLocation = 5; // Add document title TextElement titleTextElement = new TextElement(xLocation, yLocation, "Create Internal Links in PDF Document", titleFont); AddElementResult addElementResult = pdfPage.AddElement(titleTextElement); yLocation = addElementResult.EndPageBounds.Bottom + 15; // Add a text in second page TextElement secondPageTextElement = new TextElement(5, 5, "This text is the target of an internal text link", subtitleFont); secondPdfPage.AddElement(secondPageTextElement); // Add a text in third page TextElement thirdPageTextElement = new TextElement(5, 5, "This text is the target of an internal image link", subtitleFont); thirdPdfPage.AddElement(thirdPageTextElement); // Make a text in PDF an internal link to the second page of the PDF document // Add the text element string text = "Click this text to go to the second page of this document!"; float textWidth = linkTextFont.GetTextWidth(text); TextElement linkTextElement = new TextElement(xLocation, yLocation, text, linkTextFont); linkTextElement.ForeColor = Color.Navy; addElementResult = pdfPage.AddElement(linkTextElement); // Make the text element an internal link to the second page of this document RectangleF linkRectangle = new RectangleF(xLocation, yLocation, textWidth, addElementResult.EndPageBounds.Height); // Create the destination in second page ExplicitDestination secondPageDestination = new ExplicitDestination(secondPdfPage, new PointF(5, 5)); // Create the internal link from text element to second page InternalLinkElement internalLink = new InternalLinkElement(linkRectangle, secondPageDestination); // Add the internal link to PDF document pdfPage.AddElement(internalLink); yLocation = addElementResult.EndPageBounds.Bottom + 10; // Make an image in PDF an internal link to the third page of the PDF document TextElement subtitleTextElement = new TextElement(xLocation, yLocation, "Click the image below to go to the third page of this document:", subtitleFont); addElementResult = pdfPage.AddElement(subtitleTextElement); yLocation = addElementResult.EndPageBounds.Bottom + 5; // Add the image element ImageElement linkImageElement = new ImageElement(xLocation, yLocation, 120, m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/Images/logo.jpg"); addElementResult = pdfPage.AddElement(linkImageElement); // Make the image element an internal link to the third page of this document linkRectangle = addElementResult.EndPageBounds; // Create the destination in third page ExplicitDestination thirdPageDestination = new ExplicitDestination(thirdPdfPage, new PointF(5, 5)); // Create the internal link from image element to third page internalLink = new InternalLinkElement(linkRectangle, thirdPageDestination); // Add the internal link to PDF document pdfPage.AddElement(internalLink); // 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 = "Internal_Links.pdf"; return(fileResult); } finally { // Close the PDF document pdfDocument.Close(); } }
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 { // Create a HTML to PDF element to add to document HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement(collection["urlTextBox"]); // Optionally set a delay before conversion to allow asynchonous scripts to finish htmlToPdfElement.ConversionDelay = 2; // Add the HTML to PDF element to document pdfPage.AddElement(htmlToPdfElement); int goToPageNumber = int.Parse(collection["pageNumberTextBox"]); if (goToPageNumber > pdfDocument.Pages.Count) { goToPageNumber = 1; } // Get destination PDF page PdfPage goToPage = pdfDocument.Pages[goToPageNumber - 1]; // Get the destination point in PDF page float goToX = float.Parse(collection["xLocationTextBox"]); float goToY = float.Parse(collection["yLocationTextBox"]); PointF goToLocation = new PointF(goToX, goToY); // Get the destination view mode DestinationViewMode viewMode = SelectedViewMode(collection["viewModeComboBox"]); // Create the destination in PDF document ExplicitDestination goToDestination = new ExplicitDestination(goToPage, goToLocation, viewMode); // Set the zoom level when the destination is displayed if (viewMode == DestinationViewMode.XYZ) goToDestination.ZoomPercentage = int.Parse(collection["zoomLevelTextBox"]); // Set the document Go To open action pdfDocument.OpenAction.Action = new PdfActionGoTo(goToDestination); // 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 = "Go_To_Page_Open_Action.pdf"; return fileResult; } finally { // Close the PDF document pdfDocument.Close(); } }
/// <summary> /// Adds the warning title to new Pdf page. /// </summary> /// <param name="docPDF">The doc PDF.</param> /// <param name="strText">The STR text.</param> internal void AddWarningTitleToNewPDfPage(Document docPDF, String strText) { pdfPage = docPDF.AddPage(); /// Generate Text /// Create a Bold .NET font of 10 points System.Drawing.Font ttfFontBold = new System.Drawing.Font("Verdana", 12, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point); /// Create the PDF fonts based on the .NET true type fonts PdfFont newVerdanaFontBold = docPDF.AddFont(ttfFontBold); /// Add Title elements to the document TextElement WarningTitle = new TextElement(0, 200, strText, newVerdanaFontBold); WarningTitle.TextAlign = HorizontalTextAlign.Center; pdfPage.AddElement(WarningTitle); }
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 firstPdfPage = pdfDocument.AddPage(); // Create Header if (addHeaderCheckBox.Checked) { CreateHeader(pdfDocument, drawHeaderLineCheckBox.Checked); } // Create Footer if (addFooterCheckBox.Checked) { CreateFooter(pdfDocument, drawFooterLineCheckBox.Checked, addPageNumbersInFooterCheckBox.Checked); } try { // Add First HTML // Create the first HTML to PDF element HtmlToPdfElement firstHtml = new HtmlToPdfElement(0, 0, firstUrlTextBox.Text); // Optionally set a delay before conversion to allow asynchonous scripts to finish firstHtml.ConversionDelay = 2; // Optionally add a space between header and the content generated by this HTML to PDF element // The spacing for first page and the subsequent pages can be set independently // Leave this option not set for no spacing firstHtml.Y = float.Parse(firstPageSpacingTextBox.Text); firstHtml.TopSpacing = float.Parse(headerSpacingTextBox.Text); // Optionally add a space between footer and the content generated by this HTML to PDF element // Leave this option not set for no spacing firstHtml.BottomSpacing = float.Parse(footerSpacingTextBox.Text); // Install a handler where to set header visibility in the pages where the HTML element is rendered firstHtml.PrepareRenderPdfPageEvent += new PrepareRenderPdfPageDelegate(htmlToPdfElement_PrepareRenderPdfPageEvent); // Add the first HTML to PDF element to PDF document // The PrepareRenderPdfPageEvent event handler will be invoked for each rendered PDF page AddElementResult firstAddResult = firstPdfPage.AddElement(firstHtml); // Uninstall the handler firstHtml.PrepareRenderPdfPageEvent -= new PrepareRenderPdfPageDelegate(htmlToPdfElement_PrepareRenderPdfPageEvent); // Add Second HTML PdfPage secondPdfPage = null; PointF secondHtmlLocation = Point.Empty; if (startNewPageCheckBox.Checked) { // Create a PDF page where to add the second HTML secondPdfPage = pdfDocument.AddPage(); secondHtmlLocation = PointF.Empty; } else { // Add the second HTML on the PDF page where the first HTML ended secondPdfPage = pdfDocument.Pages[firstAddResult.EndPageIndex]; secondHtmlLocation = new PointF(firstAddResult.EndPageBounds.Left, firstAddResult.EndPageBounds.Bottom); } // Create the second HTML to PDF element HtmlToPdfElement secondHtml = new HtmlToPdfElement(secondHtmlLocation.X, secondHtmlLocation.Y, secondUrlTextBox.Text); // Optionally set a delay before conversion to allow asynchonous scripts to finish secondHtml.ConversionDelay = 2; // Optionally add a space between header and the content generated by this HTML to PDF element // Leave this option not set for no spacing secondHtml.TopSpacing = float.Parse(headerSpacingTextBox.Text); // Optionally add a space between footer and the content generated by this HTML to PDF element // Leave this option not set for no spacing secondHtml.BottomSpacing = float.Parse(footerSpacingTextBox.Text); // Install a handler where to set header visibility in the pages where the HTML element is rendered secondHtml.PrepareRenderPdfPageEvent += new PrepareRenderPdfPageDelegate(htmlToPdfElement_PrepareRenderPdfPageEvent); // Add the second HTML to PDF element to PDF document // The PrepareRenderPdfPageEvent event handler will be invoked for each rendered PDF page secondPdfPage.AddElement(secondHtml); // Uninstall the handler secondHtml.PrepareRenderPdfPageEvent -= new PrepareRenderPdfPageDelegate(htmlToPdfElement_PrepareRenderPdfPageEvent); // 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=Header_Footer_in_Merge_Multipe_HTML.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(); } }
public ActionResult ConvertHtmlToPdf(IFormCollection collection) { formCollection = 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 firstPdfPage = pdfDocument.AddPage(); // Create Header if (collection["addHeaderCheckBox"].Count > 0) { CreateHeader(pdfDocument, collection["drawHeaderLineCheckBox"].Count > 0); } // Create Footer if (collection["addFooterCheckBox"].Count > 0) { CreateFooter(pdfDocument, collection["drawFooterLineCheckBox"].Count > 0, collection["addPageNumbersInFooterCheckBox"].Count > 0); } try { // Add First HTML // Create the first HTML to PDF element HtmlToPdfElement firstHtml = new HtmlToPdfElement(0, 0, collection["firstUrlTextBox"]); // Optionally set a delay before conversion to allow asynchonous scripts to finish firstHtml.ConversionDelay = 2; // Optionally add a space between header and the content generated by this HTML to PDF element // The spacing for first page and the subsequent pages can be set independently // Leave this option not set for no spacing firstHtml.Y = float.Parse(collection["firstPageSpacingTextBox"]); firstHtml.TopSpacing = float.Parse(collection["headerSpacingTextBox"]); // Optionally add a space between footer and the content generated by this HTML to PDF element // Leave this option not set for no spacing firstHtml.BottomSpacing = float.Parse(collection["footerSpacingTextBox"]); // Install a handler where to set header visibility in the pages where the HTML element is rendered firstHtml.PrepareRenderPdfPageEvent += new PrepareRenderPdfPageDelegate(htmlToPdfElement_PrepareRenderPdfPageEvent); // Add the first HTML to PDF element to PDF document // The PrepareRenderPdfPageEvent event handler will be invoked for each rendered PDF page AddElementResult firstAddResult = firstPdfPage.AddElement(firstHtml); // Uninstall the handler firstHtml.PrepareRenderPdfPageEvent -= new PrepareRenderPdfPageDelegate(htmlToPdfElement_PrepareRenderPdfPageEvent); // Add Second HTML PdfPage secondPdfPage = null; PointF secondHtmlLocation = Point.Empty; if (collection["startNewPageCheckBox"].Count > 0) { // Create a PDF page where to add the second HTML secondPdfPage = pdfDocument.AddPage(); secondHtmlLocation = PointF.Empty; } else { // Add the second HTML on the PDF page where the first HTML ended secondPdfPage = pdfDocument.Pages[firstAddResult.EndPageIndex]; secondHtmlLocation = new PointF(firstAddResult.EndPageBounds.Left, firstAddResult.EndPageBounds.Bottom); } // Create the second HTML to PDF element HtmlToPdfElement secondHtml = new HtmlToPdfElement(secondHtmlLocation.X, secondHtmlLocation.Y, collection["secondUrlTextBox"]); // Optionally set a delay before conversion to allow asynchonous scripts to finish secondHtml.ConversionDelay = 2; // Optionally add a space between header and the content generated by this HTML to PDF element // Leave this option not set for no spacing secondHtml.TopSpacing = float.Parse(collection["headerSpacingTextBox"]); // Optionally add a space between footer and the content generated by this HTML to PDF element // Leave this option not set for no spacing secondHtml.BottomSpacing = float.Parse(collection["footerSpacingTextBox"]); // Install a handler where to set header visibility in the pages where the HTML element is rendered secondHtml.PrepareRenderPdfPageEvent += new PrepareRenderPdfPageDelegate(htmlToPdfElement_PrepareRenderPdfPageEvent); // Add the second HTML to PDF element to PDF document // The PrepareRenderPdfPageEvent event handler will be invoked for each rendered PDF page secondPdfPage.AddElement(secondHtml); // Uninstall the handler secondHtml.PrepareRenderPdfPageEvent -= new PrepareRenderPdfPageDelegate(htmlToPdfElement_PrepareRenderPdfPageEvent); // 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 = "Header_Footer_in_Merge_Multipe_HTML.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(); // Set the PDF Viewer Preferences // Set page layout to continuous one column, single page, two column left, two column right pdfDocument.ViewerPreferences.PageLayout = SelectedPageLayout(); // Set page mode to default, display attachments, display thumbnails, display attachments pdfDocument.ViewerPreferences.PageMode = SelectedPageMode(); // Hide the viewer menu pdfDocument.ViewerPreferences.HideMenuBar = hideMenuBarCheckBox.Checked; // Hide the viewer toolbar pdfDocument.ViewerPreferences.HideToolbar = hideToolbarCheckBox.Checked; // Hide scroll bars and navigation controls pdfDocument.ViewerPreferences.HideWindowUI = hideWindowUICheckBox.Checked; // Display the document title in viewer title bar pdfDocument.ViewerPreferences.DisplayDocTitle = displayDocTitleCheckBox.Checked; try { // Create a HTML to PDF element to add to document HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement(urlTextBox.Text); // Optionally set a delay before conversion to allow asynchonous scripts to finish htmlToPdfElement.ConversionDelay = 2; // Add the HTML to PDF element to document pdfPage.AddElement(htmlToPdfElement); // 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=Set_PDF_Viewer_Preferences.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) { // 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 createPdfButton_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(); // Add second page to PDF document PdfPage secondPdfPage = pdfDocument.AddPage(); // Add third page to PDF document PdfPage thirdPdfPage = pdfDocument.AddPage(); try { // The titles font used to mark various sections of the PDF document PdfFont titleFont = pdfDocument.AddFont(new Font("Times New Roman", 10, FontStyle.Bold, GraphicsUnit.Point)); PdfFont subtitleFont = pdfDocument.AddFont(new Font("Times New Roman", 8, FontStyle.Regular, GraphicsUnit.Point)); // The links text font PdfFont linkTextFont = pdfDocument.AddFont(new Font("Times New Roman", 8, FontStyle.Bold, GraphicsUnit.Point)); linkTextFont.IsUnderline = true; float xLocation = 5; float yLocation = 5; // Add document title TextElement titleTextElement = new TextElement(xLocation, yLocation, "Create Internal Links in PDF Document", titleFont); AddElementResult addElementResult = pdfPage.AddElement(titleTextElement); yLocation = addElementResult.EndPageBounds.Bottom + 15; // Add a text in second page TextElement secondPageTextElement = new TextElement(5, 5, "This text is the target of an internal text link", subtitleFont); secondPdfPage.AddElement(secondPageTextElement); // Add a text in third page TextElement thirdPageTextElement = new TextElement(5, 5, "This text is the target of an internal image link", subtitleFont); thirdPdfPage.AddElement(thirdPageTextElement); // Make a text in PDF an internal link to the second page of the PDF document // Add the text element string text = "Click this text to go to the second page of this document!"; float textWidth = linkTextFont.GetTextWidth(text); TextElement linkTextElement = new TextElement(xLocation, yLocation, text, linkTextFont); linkTextElement.ForeColor = Color.Navy; addElementResult = pdfPage.AddElement(linkTextElement); // Make the text element an internal link to the second page of this document RectangleF linkRectangle = new RectangleF(xLocation, yLocation, textWidth, addElementResult.EndPageBounds.Height); // Create the destination in second page ExplicitDestination secondPageDestination = new ExplicitDestination(secondPdfPage, new PointF(5, 5)); // Create the internal link from text element to second page InternalLinkElement internalLink = new InternalLinkElement(linkRectangle, secondPageDestination); // Add the internal link to PDF document pdfPage.AddElement(internalLink); yLocation = addElementResult.EndPageBounds.Bottom + 10; // Make an image in PDF an internal link to the third page of the PDF document TextElement subtitleTextElement = new TextElement(xLocation, yLocation, "Click the image below to go to the third page of this document:", subtitleFont); addElementResult = pdfPage.AddElement(subtitleTextElement); yLocation = addElementResult.EndPageBounds.Bottom + 5; // Add the image element ImageElement linkImageElement = new ImageElement(xLocation, yLocation, 120, Server.MapPath("~/DemoAppFiles/Input/Images/logo.jpg")); addElementResult = pdfPage.AddElement(linkImageElement); // Make the image element an internal link to the third page of this document linkRectangle = addElementResult.EndPageBounds; // Create the destination in third page ExplicitDestination thirdPageDestination = new ExplicitDestination(thirdPdfPage, new PointF(5, 5)); // Create the internal link from image element to third page internalLink = new InternalLinkElement(linkRectangle, thirdPageDestination); // Add the internal link to PDF document pdfPage.AddElement(internalLink); // 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=Internal_Links.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(); } }
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 { // The font used for titles in PDF document PdfFont titlesFont = pdfDocument.AddFont(new Font("Times New Roman", 10, FontStyle.Bold, GraphicsUnit.Point)); // The font used for field names in PDF document PdfFont fieldNameFont = pdfDocument.AddFont(new Font("Times New Roman", 10, FontStyle.Regular, GraphicsUnit.Point)); // The font used for buttons text in PDF document PdfFont buttonTextFont = pdfDocument.AddFont(new Font("Times New Roman", 10, FontStyle.Regular, GraphicsUnit.Point)); // The font used for PDF form text box fields PdfFont textFieldFont = pdfDocument.AddFont(StdFontBaseFamily.Helvetica); textFieldFont.Size = 8; // The font used for PDF form combo box fields PdfFont comboBoxFieldFont = pdfDocument.AddFont(StdFontBaseFamily.Helvetica); comboBoxFieldFont.Size = 8; float xLocation = 5; float yLocation = 5; // Add document title TextElement titleTextElement = new TextElement(xLocation, yLocation, "Create PDF Forms", titlesFont); AddElementResult addElementResult = pdfPage.AddElement(titleTextElement); yLocation = addElementResult.EndPageBounds.Bottom + 15; // Add a text box field to PDF form TextElement fieldNameTextElement = new TextElement(xLocation, yLocation, 60, "First name:", fieldNameFont); addElementResult = pdfPage.AddElement(fieldNameTextElement); RectangleF fieldNameRectangle = addElementResult.EndPageBounds; RectangleF fieldBoundingRectangle = new RectangleF(fieldNameRectangle.Right + 10, yLocation, 150, 15); // Create the form field PdfFormTextBox textBoxField = pdfDocument.Form.AddTextBox(pdfPage, fieldBoundingRectangle, "Enter First Name", textFieldFont); // Set unique form field name used when the form is submitted textBoxField.Name = "firstName"; // Set the form field default value textBoxField.DefaultValue = "A default first name"; // Set form field style textBoxField.Style.BackColor = Color.AliceBlue; yLocation = fieldNameRectangle.Bottom + 10; // Add a text box field to PDF form fieldNameTextElement = new TextElement(xLocation, yLocation, 60, "Last name:", fieldNameFont); addElementResult = pdfPage.AddElement(fieldNameTextElement); fieldNameRectangle = addElementResult.EndPageBounds; fieldBoundingRectangle = new RectangleF(fieldNameRectangle.Right + 10, yLocation, 150, 15); // Create the form field textBoxField = pdfDocument.Form.AddTextBox(pdfPage, fieldBoundingRectangle, "Enter Last Name", textFieldFont); // Set unique form field name used when the form is submitted textBoxField.Name = "lastName"; // Set the form field default value textBoxField.DefaultValue = "A default last name"; // Set form field style textBoxField.Style.BackColor = Color.MistyRose; yLocation = fieldNameRectangle.Bottom + 10; // Add a password text box field to PDF form fieldNameTextElement = new TextElement(xLocation, yLocation, 60, "Password:"******"", textFieldFont); // Set unique form field name used when the form is submitted passwordTextBoxField.Name = "password"; // Set form field style passwordTextBoxField.Style.BackColor = Color.AliceBlue; // Set the password mode for the text box passwordTextBoxField.IsPassword = true; yLocation = fieldNameRectangle.Bottom + 10; // Add a radio buttons group to PDF form fieldNameTextElement = new TextElement(xLocation, yLocation, 60, "Gender:", fieldNameFont); addElementResult = pdfPage.AddElement(fieldNameTextElement); fieldNameRectangle = addElementResult.EndPageBounds; // Create the radio buttons group PdfFormRadioButtonsGroup radioButtonsGroup = pdfDocument.Form.AddRadioButtonsGroup(pdfPage); // Set unique form field name used when the form is submitted radioButtonsGroup.Name = "gender"; // Set style of the radio buttons in this group radioButtonsGroup.Style.BackColor = Color.AntiqueWhite; // Add the first radio button to group RectangleF radioButtonRectangle = new RectangleF(fieldNameRectangle.Right + 10, yLocation, 50, 10); // Create the form field PdfFormRadioButton radioButtonField = radioButtonsGroup.AddRadioButton(radioButtonRectangle, "male", pdfPage); fieldNameTextElement = new TextElement(fieldNameRectangle.Right + 22, yLocation, 30, "Male", fieldNameFont); pdfPage.AddElement(fieldNameTextElement); // Add the second radio button to group radioButtonRectangle = new RectangleF(fieldNameRectangle.Right + 60, yLocation, 50, 10); // Create the form field radioButtonField = radioButtonsGroup.AddRadioButton(radioButtonRectangle, "female", pdfPage); fieldNameTextElement = new TextElement(fieldNameRectangle.Right + 72, yLocation, 30, "Female", fieldNameFont); pdfPage.AddElement(fieldNameTextElement); // Set the selected radio btton in group radioButtonsGroup.SetCheckedRadioButton("male"); yLocation = fieldNameRectangle.Bottom + 10; // Add a checkbox field to PDF form fieldNameTextElement = new TextElement(xLocation, yLocation, 60, "Vehicle:", fieldNameFont); addElementResult = pdfPage.AddElement(fieldNameTextElement); fieldNameRectangle = addElementResult.EndPageBounds; fieldBoundingRectangle = new RectangleF(fieldNameRectangle.Right + 10, yLocation, 10, 10); // Create the form field PdfFormCheckBox checkBoxField = pdfDocument.Form.AddCheckBox(pdfPage, fieldBoundingRectangle); // Set unique form field name used when the form is submitted checkBoxField.Name = "haveCar"; // Set form field style checkBoxField.Style.BackColor = Color.AntiqueWhite; // Set checkbox field checked state checkBoxField.Checked = true; fieldNameTextElement = new TextElement(fieldNameRectangle.Right + 22, yLocation, 50, "I have a car", fieldNameFont); pdfPage.AddElement(fieldNameTextElement); yLocation = fieldNameRectangle.Bottom + 10; // Add a combo box list field to PDF form fieldNameTextElement = new TextElement(xLocation, yLocation, 60, "Vehicle Type:", fieldNameFont); addElementResult = pdfPage.AddElement(fieldNameTextElement); fieldNameRectangle = addElementResult.EndPageBounds; fieldBoundingRectangle = new RectangleF(fieldNameRectangle.Right + 10, yLocation, 50, 15); string[] comboBoxItems = new string[] { "Volvo", "Saab", "Audi", "Opel" }; // Create the form field PdfFormComboBox comboBoxField = pdfDocument.Form.AddComboBox(pdfPage, fieldBoundingRectangle, comboBoxItems, comboBoxFieldFont); // Set unique form field name used when the form is submitted comboBoxField.Name = "vehicleType"; // Set the form field default value comboBoxField.DefaultValue = "Audi"; // Set form field style comboBoxField.Style.BackColor = Color.LightCyan; // Set selected item in combo box comboBoxField.Value = "Audi"; yLocation = fieldNameRectangle.Bottom + 10; // Add a multiline text box field to PDF form fieldNameTextElement = new TextElement(xLocation, yLocation + 20, 60, "Comments:", fieldNameFont); addElementResult = pdfPage.AddElement(fieldNameTextElement); fieldNameRectangle = addElementResult.EndPageBounds; fieldBoundingRectangle = new RectangleF(fieldNameRectangle.Right + 10, yLocation, 150, 60); // Create the form field PdfFormTextBox multilineTextBoxField = pdfDocument.Form.AddTextBox(pdfPage, fieldBoundingRectangle, "Enter your comments here:\r\nFirst comment line\r\nSecond comment line", textFieldFont); // Set unique form field name used when the form is submitted multilineTextBoxField.Name = "comments"; // Set form field style multilineTextBoxField.Style.BackColor = Color.AliceBlue; // Set the multiline mode for text box field multilineTextBoxField.IsMultiLine = true; yLocation = yLocation + 70; // Add a form submit button to PDF form fieldBoundingRectangle = new RectangleF(xLocation, yLocation, 75, 15); PdfFormButton submitFormButton = pdfDocument.Form.AddButton(pdfPage, fieldBoundingRectangle, "Submit", buttonTextFont); // Set unique form field name used when the form is submitted submitFormButton.Name = "submitFormButton"; // Set form field style submitFormButton.Style.BackColor = Color.Beige; // Create the form submit action PdfSubmitFormAction submitFormAction = new PdfSubmitFormAction(collection["submitUrlTextBox"]); // Form values will be submitted in HTML form format submitFormAction.Flags |= PdfFormSubmitFlags.ExportFormat; if (collection["HttpMethod"] == "getMethodRadioButton") { submitFormAction.Flags |= PdfFormSubmitFlags.GetMethod; } // Set the form submit button action submitFormButton.Action = submitFormAction; // Add a form reset button to PDF form fieldBoundingRectangle = new RectangleF(xLocation + 100, yLocation, 75, 15); PdfFormButton resetFormButton = pdfDocument.Form.AddButton(pdfPage, fieldBoundingRectangle, "Reset", buttonTextFont); // Set unique form field name used when the form is submitted resetFormButton.Name = "resetFormButton"; // Set form field style resetFormButton.Style.BackColor = Color.Beige; // Create the form reset action PdfResetFormAction resetFormAction = new PdfResetFormAction(); // Set the form reset button action resetFormButton.Action = resetFormAction; // 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 = "Create_PDF_Forms.pdf"; return(fileResult); } finally { // Close the PDF document pdfDocument.Close(); } }
protected void createPdfButton_Click(object sender, EventArgs e) { // Get the server IP and port String serverIP = textBoxServerIP.Text; uint serverPort = uint.Parse(textBoxServerPort.Text); // Create a PDF document Document pdfDocument = new Document(serverIP, serverPort); // Set optional service password if (textBoxServicePassword.Text.Length > 0) { pdfDocument.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 pdfDocument.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c="; // Add a PDF page to PDF document PdfPage pdfPage = pdfDocument.AddPage(); // Create the document footer template pdfDocument.AddFooterTemplate(50); // ----- Add HTML with Page Numbering to Footer ----- // Create a variable HTML element with page numbering string htmlStringWithPageNumbers = htmlWithPageNumbersTextBox.Text; string baseUrl = baseUrlTextBox.Text; 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 pdfDocument.Footer.AddElement(footerHtmlWithPageNumbers); // Optionally draw a line at the top of the footer if (drawFooterLineCheckBox.Checked) { float footerWidth = pdfDocument.GetPage(0).PageSize.Width; // Create a line element for the top of the footer LineElement footerLine = new LineElement(0, 0, footerWidth, 0); // Set line color footerLine.ForeColor = RgbColor.Gray; // Add line element to the bottom of the footer pdfDocument.Footer.AddElement(footerLine); } // Create a HTML to PDF element to add to document HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement(0, 0, urlTextBox.Text); // Optionally set a delay before conversion to allow asynchonous scripts to finish htmlToPdfElement.ConversionDelay = 2; // Optionally add a space between footer and the page body // Leave this option not set for no spacing htmlToPdfElement.BottomSpacing = float.Parse(footerSpacingTextBox.Text); // Add the HTML to PDF element to document // This will raise the PrepareRenderPdfPageEvent event where the header and footer visibilit per page can be changed pdfPage.AddElement(htmlToPdfElement); // Save the PDF document in a memory buffer byte[] outPdfBuffer = pdfDocument.Save(); // Write the memory buffer in a PDF file// 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=Page_Numbers_in_HTML.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 the PDF document where to add the HTML documents 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="; // Create a PDF page where to add the first HTML PdfPage firstPdfPage = pdfDocument.AddPage(); // Enable the creation of a table of contents from H1 to H6 tags found in HTML pdfDocument.TableOfContents.AutoTocItemsEnabled = collection["autoTableOfContentsCheckBox"].Count > 0; // Optionally set the table of contents title pdfDocument.TableOfContents.Title = "Table of Contents"; // Optionally set the title style using CSS sttributes pdfDocument.TableOfContents.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:black; font-family:'Times New Roman'; font-size:20px; font-weight:normal; font-style:normal; background-color:#F0F0F0"; pdfDocument.TableOfContents.SetItemStyle(1, level1TextStyle); // Optionally set the page numbers style of level 1 items in table of contents string level1PageNumberStyle = "color:black; padding-right:3px; background-color:#F0F0F0; font-size:14px; font-weight:bold"; pdfDocument.TableOfContents.SetPageNumberStyle(1, level1PageNumberStyle); try { // Create the first HTML to PDF element HtmlToPdfElement firstHtml = new HtmlToPdfElement(0, 0, collection["firstUrlTextBox"]); // Optionally set a delay before conversion to allow asynchonous scripts to finish firstHtml.ConversionDelay = 2; // Enable or disable the table of contents for the first HTML document firstHtml.TableOfContentsEnabled = collection["includeFirstHtmlTocCheckBox"].Count > 0; // Add the first HTML to PDF document AddElementResult firstAddResult = firstPdfPage.AddElement(firstHtml); PdfPage secondPdfPage = null; PointF secondHtmlLocation = Point.Empty; if (collection["startNewPageCheckBox"].Count > 0) { // Create a PDF page where to add the second HTML secondPdfPage = pdfDocument.AddPage(); secondHtmlLocation = PointF.Empty; } else { // Add the second HTML on the PDF page where the first HTML ended secondPdfPage = firstAddResult.EndPdfPage; secondHtmlLocation = new PointF(firstAddResult.EndPageBounds.Left, firstAddResult.EndPageBounds.Bottom); } // Create the second HTML to PDF element HtmlToPdfElement secondHtml = new HtmlToPdfElement(secondHtmlLocation.X, secondHtmlLocation.Y, collection["secondUrlTextBox"]); // Optionally set a delay before conversion to allow asynchonous scripts to finish secondHtml.ConversionDelay = 2; // Enable or disable the table of contents for the second HTML document secondHtml.TableOfContentsEnabled = collection["includeSecondHtmlTocCheckBox"].Count > 0; // Add the second HTML to PDF document secondPdfPage.AddElement(secondHtml); // 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 = "Merge_Table_of_Contents.pdf"; return(fileResult); } finally { // Close the PDF document pdfDocument.Close(); } }
protected void createPdfButton_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 { // The titles font used to mark various sections of the PDF document PdfFont titleFont = pdfDocument.AddFont(new Font("Times New Roman", 10, FontStyle.Bold, GraphicsUnit.Point)); PdfFont subtitleFont = pdfDocument.AddFont(new Font("Times New Roman", 8, FontStyle.Regular, GraphicsUnit.Point)); float xLocation = 5; float yLocation = 5; // Add document title TextElement titleTextElement = new TextElement(xLocation, yLocation, "Add Text Notes to a PDF Document", titleFont); AddElementResult addElementResult = pdfPage.AddElement(titleTextElement); yLocation = addElementResult.EndPageBounds.Bottom + 15; // Add the text element string text = "Click the next icon to open the the text note:"; float textWidth = subtitleFont.GetTextWidth(text); TextElement textElement = new TextElement(xLocation, yLocation, text, subtitleFont); addElementResult = pdfPage.AddElement(textElement); RectangleF textNoteRectangle = new RectangleF(xLocation + textWidth + 1, yLocation, 10, 10); // Create the text note TextNoteElement textNoteElement = new TextNoteElement(textNoteRectangle, "This is an initially closed text note"); textNoteElement.NoteIcon = TextNoteIcon.Note; textNoteElement.Open = false; pdfPage.AddElement(textNoteElement); yLocation = addElementResult.EndPageBounds.Bottom + 10; // Add the text element text = "This is an already opened text note:"; textWidth = subtitleFont.GetTextWidth(text); textElement = new TextElement(xLocation, yLocation, text, subtitleFont); addElementResult = pdfPage.AddElement(textElement); textNoteRectangle = new RectangleF(xLocation + textWidth + 1, yLocation, 10, 10); // Create the text note TextNoteElement textNoteOpenedElement = new TextNoteElement(textNoteRectangle, "This is an initially opened text note"); textNoteOpenedElement.NoteIcon = TextNoteIcon.Note; textNoteOpenedElement.Open = true; pdfPage.AddElement(textNoteOpenedElement); yLocation = addElementResult.EndPageBounds.Bottom + 10; // Add the text element text = "Click the next icon to open the the help note:"; textWidth = subtitleFont.GetTextWidth(text); textElement = new TextElement(xLocation, yLocation, text, subtitleFont); addElementResult = pdfPage.AddElement(textElement); textNoteRectangle = new RectangleF(xLocation + textWidth + 1, yLocation, 10, 10); // Create the text note TextNoteElement helpNoteElement = new TextNoteElement(textNoteRectangle, "This is an initially closed help note"); helpNoteElement.NoteIcon = TextNoteIcon.Help; helpNoteElement.Open = false; pdfPage.AddElement(helpNoteElement); yLocation = addElementResult.EndPageBounds.Bottom + 10; // Add the text element text = "This is an already opened help note:"; textWidth = subtitleFont.GetTextWidth(text); textElement = new TextElement(xLocation, yLocation, text, subtitleFont); addElementResult = pdfPage.AddElement(textElement); textNoteRectangle = new RectangleF(xLocation + textWidth + 1, yLocation, 10, 10); // Create the text note TextNoteElement helpNoteOpenedElement = new TextNoteElement(textNoteRectangle, "This is an initially opened help note"); helpNoteOpenedElement.NoteIcon = TextNoteIcon.Help; helpNoteOpenedElement.Open = true; pdfPage.AddElement(helpNoteOpenedElement); yLocation = addElementResult.EndPageBounds.Bottom + 10; // Add the text element text = "Click the next icon to open the comment:"; textWidth = subtitleFont.GetTextWidth(text); textElement = new TextElement(xLocation, yLocation, text, subtitleFont); addElementResult = pdfPage.AddElement(textElement); textNoteRectangle = new RectangleF(xLocation + textWidth + 1, yLocation, 10, 10); // Create the text note TextNoteElement commentNoteElement = new TextNoteElement(textNoteRectangle, "This is an initially closed comment note"); commentNoteElement.NoteIcon = TextNoteIcon.Comment; commentNoteElement.Open = false; pdfPage.AddElement(commentNoteElement); yLocation = addElementResult.EndPageBounds.Bottom + 10; // Add the text element text = "This is an already opened comment:"; textWidth = subtitleFont.GetTextWidth(text); textElement = new TextElement(xLocation, yLocation, text, subtitleFont); addElementResult = pdfPage.AddElement(textElement); textNoteRectangle = new RectangleF(xLocation + textWidth + 1, yLocation, 10, 10); // Create the text note TextNoteElement commentNoteOpenedElement = new TextNoteElement(textNoteRectangle, "This is an initially opened comment note"); commentNoteOpenedElement.NoteIcon = TextNoteIcon.Comment; commentNoteOpenedElement.Open = true; pdfPage.AddElement(commentNoteOpenedElement); yLocation = addElementResult.EndPageBounds.Bottom + 10; // Add the text element text = "Click the next icon to open the paragraph note: "; textWidth = subtitleFont.GetTextWidth(text); textElement = new TextElement(xLocation, yLocation, text, subtitleFont); addElementResult = pdfPage.AddElement(textElement); textNoteRectangle = new RectangleF(xLocation + textWidth + 1, yLocation, 10, 10); // Create the text note TextNoteElement paragraphNoteElement = new TextNoteElement(textNoteRectangle, "This is an initially closed paragraph note"); paragraphNoteElement.NoteIcon = TextNoteIcon.Paragraph; paragraphNoteElement.Open = false; pdfPage.AddElement(paragraphNoteElement); yLocation = addElementResult.EndPageBounds.Bottom + 10; // Add the text element text = "Click the next icon to open the new paragraph note:"; textWidth = subtitleFont.GetTextWidth(text); textElement = new TextElement(xLocation, yLocation, text, subtitleFont); addElementResult = pdfPage.AddElement(textElement); textNoteRectangle = new RectangleF(xLocation + textWidth + 1, yLocation, 10, 10); // Create the text note TextNoteElement newParagraphNoteElement = new TextNoteElement(textNoteRectangle, "This is an initially closed new paragraph note"); newParagraphNoteElement.NoteIcon = TextNoteIcon.NewParagraph; newParagraphNoteElement.Open = false; pdfPage.AddElement(newParagraphNoteElement); yLocation = addElementResult.EndPageBounds.Bottom + 10; // Add the text element text = "Click the next icon to open the key note:"; textWidth = subtitleFont.GetTextWidth(text); textElement = new TextElement(xLocation, yLocation, text, subtitleFont); addElementResult = pdfPage.AddElement(textElement); textNoteRectangle = new RectangleF(xLocation + textWidth + 1, yLocation, 10, 10); // Create the text note TextNoteElement keyNoteElement = new TextNoteElement(textNoteRectangle, "This is an initially closed key note"); keyNoteElement.NoteIcon = TextNoteIcon.Key; keyNoteElement.Open = false; pdfPage.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(); } finally { // Close the PDF document pdfDocument.Close(); } }