private void DrawHeader(HtmlToPdfConverter htmlToPdfConverter, PdfUrl urls)
        {
            string headerHtmlUrl = urls.HeaderUrl;

            htmlToPdfConverter.PdfHeaderOptions.HeaderBackColor = Color.White;
            HtmlToPdfElement headerHtml = new HtmlToPdfElement(headerHtmlUrl);

            headerHtml.NavigationCompletedEvent += new NavigationCompletedDelegate(headerHtml_NavigationCompletedEvent);
            htmlToPdfConverter.PdfHeaderOptions.AddElement(headerHtml);
            headerHtml.NavigationCompletedEvent += new NavigationCompletedDelegate(headerHtml_NavigationCompletedEvent);

            void headerHtml_NavigationCompletedEvent(NavigationCompletedParams eventParams)
            {
                float headerHtmlWidth  = eventParams.HtmlContentWidthPt;
                float headerHtmlHeight = eventParams.HtmlContentHeightPt;
                float headerWidth      = htmlToPdfConverter.PdfDocumentOptions.PdfPageSize.Width - htmlToPdfConverter.PdfDocumentOptions.LeftMargin -
                                         htmlToPdfConverter.PdfDocumentOptions.RightMargin;

                float resizeFactor = 1;

                if (headerHtmlWidth > headerWidth)
                {
                    resizeFactor = headerWidth / headerHtmlWidth;
                }

                float headerHeight = headerHtmlHeight * resizeFactor;

                if (!(headerHeight < htmlToPdfConverter.PdfDocumentOptions.PdfPageSize.Height - htmlToPdfConverter.PdfDocumentOptions.TopMargin -
                      htmlToPdfConverter.PdfDocumentOptions.BottomMargin))
                {
                    throw new Exception("The header height cannot be bigger than PDF page height");
                }
                htmlToPdfConverter.PdfDocumentOptions.DocumentObject.Header.Height = headerHeight;
            }
        }
Beispiel #2
0
        /// <summary>
        /// Add a header to document
        /// </summary>
        /// <param name="pdfDocument">The PDF document object</param>
        /// <param name="drawHeaderLine">A flag indicating if a line should be drawn at the bottom of the header</param>
        private void AddHeader(Document pdfDocument, bool drawHeaderLine)
        {
            string headerHtmlUrl = Server.MapPath("~/DemoAppFiles/Input/HTML_Files/Header_HTML.html");

            // Create the document footer template
            pdfDocument.AddHeaderTemplate(60);

            // Create a HTML 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 header
            pdfDocument.Header.AddElement(headerHtml);

            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);
            }
        }
Beispiel #3
0
        /// <summary>
        /// Creates the document header
        /// </summary>
        /// <param name="pdfDocument">The PDF document object</param>
        /// <param name="drawHeaderLine">A flag indicating if a line should be drawn at the bottom of the header</param>
        private void CreateHeader(Document pdfDocument, bool drawHeaderLine)
        {
            string headerHtmlUrl = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/HTML_Files/Header_HTML.html";

            // Add a header to document having 60 points in height
            pdfDocument.AddHeaderTemplate(60);

            // Create a HTML 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 header
            pdfDocument.Header.AddElement(headerHtml);

            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);
            }
        }
Beispiel #4
0
        internal void AddHeaderElementsLijst5(PdfConverter pdfConverter, string HTMLInHeader)
        {
            pdfConverter.PdfDocumentOptions.ShowHeader = true;

            //write the page number
            //TextElement HeaderText = new TextElement(0, pdfConverter.PdfFooterOptions.FooterHeight  - 15,
            //            "Pagina nummer &p; van &P; ",
            //            //new System.Drawing.Font(new System.Drawing.FontFamily(System.Drawing.Text.GenericFontFamilies.SansSerif),// "Times New Roman"),
            //            new System.Drawing.Font(new System.Drawing.FontFamily("Calibri"),// "Nog steeds Times New Roman!!!"),
            //            8, System.Drawing.GraphicsUnit.Point));
            TextElement HeaderText = new TextElement(0, pdfConverter.PdfHeaderOptions.HeaderHeight - 15,
                                                     "Pagina nummer &p; van &P; ",
                                                                                                                       //new System.Drawing.Font(new System.Drawing.FontFamily(System.Drawing.Text.GenericFontFamilies.SansSerif),// "Times New Roman"),
                                                     new System.Drawing.Font(new System.Drawing.FontFamily("Calibri"), // "Nog steeds Times New Roman!!!"),
                                                                             8, System.Drawing.GraphicsUnit.Point));

            HeaderText.EmbedSysFont = true;
            HeaderText.TextAlign    = HorizontalTextAlign.Right;
            pdfConverter.PdfHeaderOptions.AddElement(HeaderText);

            HtmlToPdfElement headerHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfHeaderOptions.HeaderHeight,
                                                               HTMLInHeader, null, 1024, 0);

            headerHtml.FitHeight  = true;
            headerHtml.EmbedFonts = true; //new  cbEmbedFonts.Checked;
            pdfConverter.PdfHeaderOptions.AddElement(headerHtml);
        }
Beispiel #5
0
        private void AddHeaderElements(PdfConverter pdfConverter)
        {
            // set the header HTML area
            HtmlToPdfElement headerHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfHeaderOptions.HeaderHeight,
                    "<b>HTML in Header</b>", null, 1024, 0);
            headerHtml.FitHeight = true;
            headerHtml.EmbedFonts = cbEmbedFonts.Checked;
            pdfConverter.PdfHeaderOptions.AddElement(headerHtml);

            if (cbDrawHeaderLine.Checked)
            {
                // set the header line
                float pdfPageWidth = 0;
                if (pdfConverter.PdfDocumentOptions.PdfPageOrientation == PdfPageOrientation.Portrait)
                    pdfPageWidth = pdfConverter.PdfDocumentOptions.PdfPageSize.Width;
                else
                    pdfPageWidth = pdfConverter.PdfDocumentOptions.PdfPageSize.Height;

                LineElement headerLine = new LineElement(0, pdfConverter.PdfHeaderOptions.HeaderHeight,
                            pdfPageWidth - pdfConverter.PdfDocumentOptions.LeftMargin - pdfConverter.PdfDocumentOptions.RightMargin,
                            pdfConverter.PdfHeaderOptions.HeaderHeight);
                headerLine.LineStyle.LineWidth = 0.5f;
                headerLine.ForeColor = Color.FromKnownColor((KnownColor)Enum.Parse(typeof(KnownColor), ddlHeaderLineColor.SelectedItem.ToString()));
                pdfConverter.PdfHeaderOptions.AddElement(headerLine);
            }
        }
Beispiel #6
0
        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();
            }
        }
Beispiel #7
0
        protected void stampPdfButton_Click(object sender, EventArgs e)
        {
            // Get the server IP and port
            String serverIP   = textBoxServerIP.Text;
            uint   serverPort = uint.Parse(textBoxServerPort.Text);

            // Load the PDF document to stamp
            string   pdfFileToStampPath = Server.MapPath("~/DemoAppFiles/Input/PDF_Files/PDF_Document.pdf");
            Document pdfDocument        = new Document(serverIP, serverPort, pdfFileToStampPath);

            // 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=";

            // Get the stamp width and height
            float stampWidth  = float.Parse(stampWidthTextBox.Text);
            float stampHeight = float.Parse(stampHeightTextBox.Text);

            // Center the stamp at the top of PDF page
            float stampXLocation = (pdfDocument.GetPage(0).PageSize.Width - stampWidth) / 2;
            float stampYLocation = 0;

            // Create the stamp template to be repeated in each PDF page
            Template stampTemplate = pdfDocument.AddTemplate(stampXLocation, stampYLocation, stampWidth, stampHeight);

            // Create the HTML element to add in stamp template
            HtmlToPdfElement stampHtmlElement = new HtmlToPdfElement(htmlStringTextBox.Text, baseUrlTextBox.Text);

            // Set the HTML viewer width for the HTML added in stamp
            stampHtmlElement.HtmlViewerWidth = 600;
            // Fit the HTML content in stamp template
            stampHtmlElement.FitWidth  = true;
            stampHtmlElement.FitHeight = true;

            // Add HTML to stamp template
            stampTemplate.AddElement(stampHtmlElement);

            // Save the PDF document in a memory buffer
            byte[] outPdfBuffer = pdfDocument.Save();

            // Send the PDF as response to browser

            // Set response content type
            Response.AddHeader("Content-Type", "application/pdf");

            // Instruct the browser to open the PDF file as an attachment or inline
            Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Stamp_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();
        }
Beispiel #8
0
        private void AddFooterElements(PdfConverter pdfConverter)
        {
            //write the page number
            TextElement footerText = new TextElement(0, pdfConverter.PdfFooterOptions.FooterHeight - 15, "This is page &p; of &P;  ",
                new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 10, System.Drawing.GraphicsUnit.Point));
            footerText.EmbedSysFont = true;
            footerText.TextAlign = HorizontalTextAlign.Right;
            pdfConverter.PdfFooterOptions.AddElement(footerText);

            // set the footer HTML area
            HtmlToPdfElement footerHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfFooterOptions.FooterHeight,
                        "<i>HTML in Footer</i>", null, 1024, 0);
            footerHtml.FitHeight = true;
            footerHtml.EmbedFonts = cbEmbedFonts.Checked;
            pdfConverter.PdfFooterOptions.AddElement(footerHtml);

            if (cbDrawFooterLine.Checked)
            {
                // set the footer line
                float pdfPageWidth = 0;
                if (pdfConverter.PdfDocumentOptions.PdfPageOrientation == PdfPageOrientation.Portrait)
                    pdfPageWidth = pdfConverter.PdfDocumentOptions.PdfPageSize.Width;
                else
                    pdfPageWidth = pdfConverter.PdfDocumentOptions.PdfPageSize.Height;

                LineElement footerLine = new LineElement(0, 0,
                            pdfPageWidth - pdfConverter.PdfDocumentOptions.LeftMargin - pdfConverter.PdfDocumentOptions.RightMargin, 0);
                footerLine.LineStyle.LineWidth = 0.5f;
                footerLine.ForeColor = Color.FromKnownColor((KnownColor)Enum.Parse(typeof(KnownColor), ddlFooterLineColor.SelectedItem.ToString()));
                pdfConverter.PdfFooterOptions.AddElement(footerLine);
            }
        }
Beispiel #9
0
        /// <summary>
        /// Draw the footer elements
        /// </summary>
        /// <param name="htmlToPdfConverter">The HTML to PDF Converter object</param>
        /// <param name="addPageNumbers">A flag indicating if the page numbering is present in footer</param>
        /// <param name="drawFooterLine">A flag indicating if a line should be drawn at the top of the footer</param>
        private void DrawFooter(HtmlToPdfConverter htmlToPdfConverter, bool addPageNumbers, bool drawFooterLine)
        {
            string footerHtmlString = System.IO.File.ReadAllText(Server.MapPath("~/DemoAppFiles/Input/HTML_Files/Footer_HTML.html"));
            string footerBaseUrl    = "http://www.evopdf.com/demo/DemoAppFiles/Input/HTML_Files/";

            // Set the footer height in points
            htmlToPdfConverter.PdfFooterOptions.FooterHeight = 60;

            // Set footer background color
            htmlToPdfConverter.PdfFooterOptions.FooterBackColor = RgbColor.WhiteSmoke;

            // Create a HTML element to be added in footer
            HtmlToPdfElement footerHtml = new HtmlToPdfElement(footerHtmlString, footerBaseUrl);

            // Set the HTML element to fit the container height
            footerHtml.FitHeight = true;

            // Add HTML element to footer
            htmlToPdfConverter.PdfFooterOptions.AddElement(footerHtml);

            // Add page numbering
            if (addPageNumbers)
            {
                // Create a text element with page numbering place holders &p; and & P;
                TextElement footerText = new TextElement(0, 30, "Page &p; of &P;  ", new PdfFont("Times New Roman", 10, true));

                // Align the text at the right of the footer
                footerText.TextAlign = HorizontalTextAlign.Right;

                // Set page numbering text color
                footerText.ForeColor = RgbColor.Navy;

                // Embed the text element font in PDF
                footerText.EmbedSysFont = true;

                // Add the text element to footer
                htmlToPdfConverter.PdfFooterOptions.AddElement(footerText);
            }

            if (drawFooterLine)
            {
                // Calculate the footer width based on PDF page size and margins
                float footerWidth = htmlToPdfConverter.PdfDocumentOptions.PdfPageSize.Width -
                                    htmlToPdfConverter.PdfDocumentOptions.LeftMargin - htmlToPdfConverter.PdfDocumentOptions.RightMargin;

                // Create a line element for the top of the footer
                LineElement footerLine = new LineElement(0, 0, footerWidth, 0);

                // Set line color
                footerLine.ForeColor = RgbColor.Gray;

                // Add line element to the bottom of the footer
                htmlToPdfConverter.PdfFooterOptions.AddElement(footerLine);
            }

            // set footer visibility in PDF pages
            htmlToPdfConverter.PdfFooterOptions.ShowInFirstPage = showFooterInFirstPageCheckBox.Checked;
            htmlToPdfConverter.PdfFooterOptions.ShowInOddPages  = showFooterInOddPagesCheckBox.Checked;
            htmlToPdfConverter.PdfFooterOptions.ShowInEvenPages = showFooterInEvenPagesCheckBox.Checked;
        }
        /// <summary>
        /// Add a header to document
        /// </summary>
        /// <param name="pdfDocument">The PDF document object</param>
        /// <param name="drawHeaderLine">A flag indicating if a line should be drawn at the bottom of the header</param>
        private void AddHeader(Document pdfDocument, bool drawHeaderLine)
        {
            string headerHtmlString = System.IO.File.ReadAllText(Server.MapPath("~/DemoAppFiles/Input/HTML_Files/Header_HTML.html"));
            string headerBaseUrl    = "http://www.evopdf.com/demo/DemoAppFiles/Input/HTML_Files/";

            // Create the document footer template
            pdfDocument.AddHeaderTemplate(60);

            // Create a HTML element to be added in header
            HtmlToPdfElement headerHtml = new HtmlToPdfElement(headerHtmlString, headerBaseUrl);

            // Set the HTML element to fit the container height
            headerHtml.FitHeight = true;

            // Add HTML element to header
            pdfDocument.Header.AddElement(headerHtml);

            if (drawHeaderLine)
            {
                float headerWidth  = pdfDocument.GetPage(0).PageSize.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 = RgbColor.Gray;

                // Add line element to the bottom of the header
                pdfDocument.Header.AddElement(headerLine);
            }
        }
Beispiel #11
0
        /// <summary>
        /// Draw the alternative page header elements
        /// </summary>
        /// <param name="headerTemplate">The page header template</param>
        /// <param name="drawHeaderLine">A flag indicating if a line should be drawn at the bottom of the header</param>
        private void DrawAlternativePageHeader(Template headerTemplate, bool drawHeaderLine)
        {
            string headerHtmlUrl = Server.MapPath("~/DemoAppFiles/Input/HTML_Files/Header_Alt_HTML.html");

            // Create a HTML 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 header
            headerTemplate.AddElement(headerHtml);

            if (drawHeaderLine)
            {
                float headerWidth  = headerTemplate.Width;
                float headerHeight = headerTemplate.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
                headerTemplate.AddElement(headerLine);
            }
        }
        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();
            }
        }
        public ActionResult StampPdf(IFormCollection collection)
        {
            Document pdfDocument = null;

            try
            {
                // Load the PDF document to stamp
                string pdfFileToStampPath = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/PDF_Files/PDF_Document.pdf";
                pdfDocument = new Document(pdfFileToStampPath);

                // 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=";

                // Get the stamp width and height
                float stampWidth  = float.Parse(collection["stampWidthTextBox"]);
                float stampHeight = float.Parse(collection["stampHeightTextBox"]);

                // Center the stamp at the top of PDF page
                float stampXLocation = (pdfDocument.Pages[0].ClientRectangle.Width - stampWidth) / 2;
                float stampYLocation = 0;

                RectangleF stampRectangle = new RectangleF(stampXLocation, stampYLocation, stampWidth, stampHeight);

                // Create the stamp template to be repeated in each PDF page
                Template stampTemplate = pdfDocument.AddTemplate(stampRectangle);

                // Create the HTML element to add in stamp template
                HtmlToPdfElement stampHtmlElement = new HtmlToPdfElement(collection["htmlStringTextBox"], collection["baseUrlTextBox"]);

                // Set the HTML viewer width for the HTML added in stamp
                stampHtmlElement.HtmlViewerWidth = 600;
                // Fit the HTML content in stamp template
                stampHtmlElement.FitWidth  = true;
                stampHtmlElement.FitHeight = true;

                // Add HTML to stamp template
                stampTemplate.AddElement(stampHtmlElement);

                // Save the PDF document in a memory buffer
                byte[] outPdfBuffer = pdfDocument.Save();

                // Send the PDF file to browser
                FileResult fileResult = new FileContentResult(outPdfBuffer, "application/pdf");
                fileResult.FileDownloadName = "Stamp_PDF.pdf";

                return(fileResult);
            }
            finally
            {
                // Close the document to stamp
                if (pdfDocument != null)
                {
                    pdfDocument.Close();
                }
            }
        }
Beispiel #15
0
        protected void convertToPdfButton_Click(object sender, EventArgs e)
        {
            // Get the server IP and port
            String serverIP   = textBoxServerIP.Text;
            uint   serverPort = uint.Parse(textBoxServerPort.Text);

            // Create a 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();
        }
Beispiel #16
0
        /// <summary>
        /// Add a footer to document
        /// </summary>
        /// <param name="pdfDocument">The PDF document object</param>
        /// <param name="addPageNumbers">A flag indicating if the page numbering is present in footer</param>
        /// <param name="drawFooterLine">A flag indicating if a line should be drawn at the top of the footer</param>
        private void AddFooter(Document pdfDocument, bool addPageNumbers, bool drawFooterLine)
        {
            string footerHtmlUrl = Server.MapPath("~/DemoAppFiles/Input/HTML_Files/Footer_HTML.html");

            // Create the document footer template
            pdfDocument.AddFooterTemplate(60);

            // Set footer background color
            RectangleElement backColorRectangle = new RectangleElement(0, 0, pdfDocument.Footer.Width, pdfDocument.Footer.Height);

            backColorRectangle.BackColor = Color.WhiteSmoke;
            pdfDocument.Footer.AddElement(backColorRectangle);

            // Create a HTML element to be added in footer
            HtmlToPdfElement footerHtml = new HtmlToPdfElement(footerHtmlUrl);

            // Set the HTML element to fit the container height
            footerHtml.FitHeight = true;

            // Add HTML element to footer
            pdfDocument.Footer.AddElement(footerHtml);

            // Add page numbering
            if (addPageNumbers)
            {
                // Create a text element with page numbering place holders &p; and & P;
                TextElement footerText = new TextElement(0, 30, "Page &p; of &P;  ",
                                                         new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 10, System.Drawing.GraphicsUnit.Point));

                // Align the text at the right of the footer
                footerText.TextAlign = HorizontalTextAlign.Right;

                // Set page numbering text color
                footerText.ForeColor = Color.Navy;

                // Embed the text element font in PDF
                footerText.EmbedSysFont = true;

                // Add the text element to footer
                pdfDocument.Footer.AddElement(footerText);
            }

            if (drawFooterLine)
            {
                float footerWidth = pdfDocument.Footer.Width;

                // Create a line element for the top of the footer
                LineElement footerLine = new LineElement(0, 0, footerWidth, 0);

                // Set line color
                footerLine.ForeColor = Color.Gray;

                // Add line element to the bottom of the footer
                pdfDocument.Footer.AddElement(footerLine);
            }
        }
Beispiel #17
0
        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();
            }
        }
Beispiel #18
0
        /// <summary>
        /// Draw the document footer elements
        /// </summary>
        /// <param name="htmlToPdfConverter">The HTML to PDF Converter object</param>
        /// <param name="addPageNumbers">A flag indicating if the page numbering is present in footer</param>
        /// <param name="drawFooterLine">A flag indicating if a line should be drawn at the top of the footer</param>
        private void DrawFooter(HtmlToPdfConverter htmlToPdfConverter, bool addPageNumbers, bool drawFooterLine)
        {
            string footerHtmlUrl = Server.MapPath("~/DemoAppFiles/Input/HTML_Files/Footer_HTML.html");

            // Set the footer height in points
            htmlToPdfConverter.PdfFooterOptions.FooterHeight = 60;

            // Set footer background color
            htmlToPdfConverter.PdfFooterOptions.FooterBackColor = Color.WhiteSmoke;

            // Create a HTML element to be added in footer
            HtmlToPdfElement footerHtml = new HtmlToPdfElement(footerHtmlUrl);

            // Set the HTML element to fit the container height
            footerHtml.FitHeight = true;

            // Add HTML element to footer
            htmlToPdfConverter.PdfFooterOptions.AddElement(footerHtml);

            // Add page numbering
            if (addPageNumbers)
            {
                // Create a text element with page numbering place holders &p; and & P;
                TextElement footerText = new TextElement(0, 30, "Page &p; of &P;  ",
                                                         new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 10, System.Drawing.GraphicsUnit.Point));

                // Align the text at the right of the footer
                footerText.TextAlign = HorizontalTextAlign.Right;

                // Set page numbering text color
                footerText.ForeColor = Color.Navy;

                // Embed the text element font in PDF
                footerText.EmbedSysFont = true;

                // Add the text element to footer
                htmlToPdfConverter.PdfFooterOptions.AddElement(footerText);
            }

            if (drawFooterLine)
            {
                // Calculate the footer width based on PDF page size and margins
                float footerWidth = htmlToPdfConverter.PdfDocumentOptions.PdfPageSize.Width -
                                    htmlToPdfConverter.PdfDocumentOptions.LeftMargin - htmlToPdfConverter.PdfDocumentOptions.RightMargin;

                // Create a line element for the top of the footer
                LineElement footerLine = new LineElement(0, 0, footerWidth, 0);

                // Set line color
                footerLine.ForeColor = Color.Gray;

                // Add line element to the bottom of the footer
                htmlToPdfConverter.PdfFooterOptions.AddElement(footerLine);
            }
        }
Beispiel #19
0
        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();
            }
        }
Beispiel #20
0
        private void AddHtmlHeader(Document document)
        {
            string headerAndFooterHtmlUrl = @"HeaderAndFooterHtml.htm";

            //create a template to be added in the header and footer
            document.HeaderTemplate = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 100);
            // create a HTML to PDF converter element to be added to the header template
            HtmlToPdfElement headerHtmlToPdf = new HtmlToPdfElement(headerAndFooterHtmlUrl);

            document.HeaderTemplate.AddElement(headerHtmlToPdf);
        }
        private void AddHtmlHeader(Document document)
        {
            string headerAndFooterHtmlUrl = Path.Combine(Application.StartupPath, @"..\..\HeaderFooter\HeaderAndFooterHtml.htm");

            //create a template to be added in the header and footer
            document.Header = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 60);
            // create a HTML to PDF converter element to be added to the header template
            HtmlToPdfElement headerHtmlToPdf = new HtmlToPdfElement(0, 0, document.Header.ClientRectangle.Width,
                    document.Header.ClientRectangle.Height, headerAndFooterHtmlUrl);
            headerHtmlToPdf.FitHeight = true;
            document.Header.AddElement(headerHtmlToPdf);
        }
Beispiel #22
0
        private static void AddHeader(HtmlToPdfConverter converter, string htmlHeader, string baseUrl)
        {
            converter.PdfDocumentOptions.ShowHeader = true;
            var pdfElement = new HtmlToPdfElement(htmlHeader, baseUrl);

            converter.PdfHeaderOptions.AddElement(pdfElement);

            converter.PrepareRenderPdfPageEvent += e =>
            {
                e.Page.ShowHeader = e.IsNewPage;
            };
        }
Beispiel #23
0
        public static HtmlToPdfConverter GetInitializedHtmlConverter(string html_string, out string html_body)
        {
            HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();

            htmlToPdfConverter.PdfDocumentOptions.Width                = 750;
            htmlToPdfConverter.HtmlViewerWidth                         = 650;
            htmlToPdfConverter.PdfDocumentOptions.LeftMargin           = 50;
            htmlToPdfConverter.PdfDocumentOptions.RightMargin          = 50;
            htmlToPdfConverter.PdfDocumentOptions.TopMargin            = 25;
            htmlToPdfConverter.PdfDocumentOptions.BottomMargin         = 10;
            htmlToPdfConverter.PdfDocumentOptions.AvoidImageBreak      = true;
            htmlToPdfConverter.PdfDocumentOptions.AvoidTextBreak       = true;
            htmlToPdfConverter.PdfDocumentOptions.JpegCompressionLevel = 0;

            // Install a handler where to change the header and footer in first page
            htmlToPdfConverter.PrepareRenderPdfPageEvent += new PrepareRenderPdfPageDelegate(htmlToPdfConverter_PrepareRenderPdfPageEvent);

            html_body = "";
            string header        = "";
            string footer        = "";
            int    header_height = 0;
            int    footer_height = 0;

            DocumentTemplate.GetPageParts(html_string, out header, out footer, out html_body, out header_height, out footer_height);

            if (!string.IsNullOrEmpty(header))
            {
                htmlToPdfConverter.PdfDocumentOptions.ShowHeader = true;
                htmlToPdfConverter.PdfHeaderOptions.HeaderHeight = header_height;
                HtmlToPdfElement headerElem = new HtmlToPdfElement(0, 0, 0, header, "", 680);
                headerElem.FitHeight = true;
                htmlToPdfConverter.PdfHeaderOptions.AddElement(headerElem);
            }
            if (!string.IsNullOrEmpty(footer))
            {
                htmlToPdfConverter.PdfDocumentOptions.ShowFooter = true;
                HtmlToPdfElement footerElem = new HtmlToPdfElement(footer, "");
                if (footer_height > 0)
                {
                    htmlToPdfConverter.PdfFooterOptions.FooterHeight = footer_height;
                }
                else
                {
                    footerElem.FitHeight = true;
                }
                htmlToPdfConverter.PdfFooterOptions.AddElement(footerElem);
            }

            htmlToPdfConverter.LicenseKey = "sjwvPS4uPSskPSgzLT0uLDMsLzMkJCQk";
            htmlToPdfConverter.PdfDocumentOptions.AvoidImageBreak = true;

            return(htmlToPdfConverter);
        }
Beispiel #24
0
        protected string ViewPdf(string pageTitle, string viewName, object model, int EncID)
        {
            string htmlText = this.htmlViewRenderer.RenderViewToString(this, viewName, model);

            LicensingManager.LicenseKey =
            "p7puTclbnKkiwDEBbqrmBOjMEWlhGRpUPyFudeNYQrrbiViiVgi6+DUR/DZCcJ3W";
            Document document = new Document();
            document.CompressionLevel = CompressionLevel.NormalCompression;
            document.Margins = new Margins(10, 10, 0, 0);
            document.Security.CanPrint = true;
            document.Security.UserPassword = "";
            document.DocumentInformation.Author = "HTML to PDF Converter";
            document.ViewerPreferences.HideToolbar = false;
            //Add a first page to the document. The next pages will inherit the            settings
            //from this page
            PdfPage page = document.Pages.AddNewPage(PageSize.A4, new Margins(10, 10, 0, 0), PageOrientation.Portrait);
            // add a font to the document that can be used for the texts elements
                PdfFont font = document.Fonts.Add(new Font(new FontFamily("Times New Roman"), 10,GraphicsUnit.Point));

                float xLocation = 50;

                float yLocation = 25;

                float width = 600;

                float height = -1;
            // convert HTML to PDF
            HtmlToPdfElement htmlToPdfElement;
                // convert a HTML string to PDF
                string htmlStringToConvert =htmlText;
                //string baseURL = textBoxBaseURL.Text.Trim();
                htmlToPdfElement = new HtmlToPdfElement(xLocation, yLocation, width, height, htmlText.ToString(), null);
                AddElementResult addResult;
                addResult = page.AddElement(htmlToPdfElement);
                string Path = Server.MapPath("~").ToString() + "pdfs/" + EncID + "_" + DateTime.Now.ToString("MM_dd_yyyy") + ".pdf";
                string retPath =  EncID + "_" + DateTime.Now.ToString("MM_dd_yyyy") + ".pdf";
                string savelocation = Path;
               System.Web.HttpContext.Current.ApplicationInstance.CompleteRequest();
               document.Save(Path);
               return retPath;
              // string name =System.IO.Path.GetFileName(Path);
              //Response.ClearContent();
              //  Response.ClearHeaders();
              //  Response.ContentType = "application/pdf";
              // Response.AppendHeader("content-disposition", "inline; filename=" + name);
              //  Response.WriteFile(Path);
              //  Response.End();
              //  Response.Flush();
              //  Response.Close();

                //ScriptManager.RegisterClientScriptBlock(null, this.GetType(), "script", "<script>alert();</script>", false);
        }
Beispiel #25
0
        /// <summary>
        /// Creates the document footer
        /// </summary>
        /// <param name="htmlToPdfConverter">The HTML to PDF Converter object</param>
        /// <param name="addPageNumbers">A flag indicating if the page numbering is present in footer</param>
        /// <param name="drawFooterLine">A flag indicating if a line should be drawn at the top of the footer</param>
        private void CreateFooter(Document pdfDocument, bool addPageNumbers, bool drawFooterLine)
        {
            string footerHtmlString = System.IO.File.ReadAllText(Server.MapPath("~/DemoAppFiles/Input/HTML_Files/Footer_HTML.html"));
            string footerBaseUrl    = "http://www.evopdf.com/demo/DemoAppFiles/Input/HTML_Files/";

            // Add a footer to document having 60 points in height
            pdfDocument.AddFooterTemplate(60);

            // Create a HTML element to be added in footer
            HtmlToPdfElement footerHtml = new HtmlToPdfElement(footerHtmlString, footerBaseUrl);

            // Set the HTML element to fit the container height
            footerHtml.FitHeight = true;

            // Add HTML element to footer
            pdfDocument.Footer.AddElement(footerHtml);

            // Add page numbering
            if (addPageNumbers)
            {
                // Create a text element with page numbering place holders &p; and & P;
                TextElement footerText = new TextElement(0, 30, "Page &p; of &P;  ", new PdfFont("Times New Roman", 10, true));

                // Align the text at the right of the footer
                footerText.TextAlign = HorizontalTextAlign.Right;

                // Set page numbering text color
                footerText.ForeColor = RgbColor.Navy;

                // Embed the text element font in PDF
                footerText.EmbedSysFont = true;

                // Add the text element to footer
                pdfDocument.Footer.AddElement(footerText);
            }

            if (drawFooterLine)
            {
                // Calculate the footer width based on PDF page size and margins
                PdfPage firstPage   = pdfDocument.GetPage(0);
                float   footerWidth = firstPage.PageSize.Width - firstPage.Margins.Left - firstPage.Margins.Right;

                // 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);
            }
        }
Beispiel #26
0
        /// <summary>
        /// Creates the document footer
        /// </summary>
        /// <param name="htmlToPdfConverter">The HTML to PDF Converter object</param>
        /// <param name="addPageNumbers">A flag indicating if the page numbering is present in footer</param>
        /// <param name="drawFooterLine">A flag indicating if a line should be drawn at the top of the footer</param>
        private void CreateFooter(Document pdfDocument, bool addPageNumbers, bool drawFooterLine)
        {
            string footerHtmlUrl = m_hostingEnvironment.ContentRootPath + "/wwwroot" + "/DemoAppFiles/Input/HTML_Files/Footer_HTML.html";

            // Add a footer to document having 60 points in height
            pdfDocument.AddFooterTemplate(60);

            // Create a HTML element to be added in footer
            HtmlToPdfElement footerHtml = new HtmlToPdfElement(footerHtmlUrl);

            // Set the HTML element to fit the container height
            footerHtml.FitHeight = true;

            // Add HTML element to footer
            pdfDocument.Footer.AddElement(footerHtml);

            // Add page numbering
            if (addPageNumbers)
            {
                // Create a text element with page numbering place holders &p; and & P;
                TextElement footerText = new TextElement(0, 30, "Page &p; of &P;  ",
                                                         new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 10, System.Drawing.GraphicsUnit.Point));

                // Align the text at the right of the footer
                footerText.TextAlign = HorizontalTextAlign.Right;

                // Set page numbering text color
                footerText.ForeColor = Color.Navy;

                // Embed the text element font in PDF
                footerText.EmbedSysFont = true;

                // Add the text element to footer
                pdfDocument.Footer.AddElement(footerText);
            }

            if (drawFooterLine)
            {
                // Calculate the footer width based on PDF page size and margins
                float footerWidth = pdfDocument.Footer.Width;

                // Create a line element for the top of the footer
                LineElement footerLine = new LineElement(0, 0, footerWidth, 0);

                // Set line color
                footerLine.ForeColor = Color.Gray;

                // Add line element to the bottom of the footer
                pdfDocument.Footer.AddElement(footerLine);
            }
        }
Beispiel #27
0
    private void AddSummaryFooter(PdfConverter pdfConverter, string contentPath)
    {
        //enable footer
        pdfConverter.PdfDocumentOptions.ShowFooter = true;
        pdfConverter.PdfFooterOptions.FooterHeight = 85;
      
        //write the footer

        var summaryFooterUrl = contentPath + "/templates/SummaryFooter.htm";
        var footerHtml = new HtmlToPdfElement(0, 5, 0, pdfConverter.PdfFooterOptions.FooterHeight, summaryFooterUrl, 1024, 0);

        footerHtml.FitHeight = true;
        pdfConverter.PdfFooterOptions.AddElement(footerHtml);
    }
        private void AddHeader(PdfConverter pdfConverter)
        {
            string headerAndFooterHtmlUrl = System.IO.Path.Combine(Application.StartupPath,
                        @"..\..\HeaderFooter\HeaderAndFooterHtml.htm");

            //enable header
            pdfConverter.PdfDocumentOptions.ShowHeader = true;
            // set the header height in points
            pdfConverter.PdfHeaderOptions.HeaderHeight = 60;
            // set the header HTML area
            HtmlToPdfElement headerHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfHeaderOptions.HeaderHeight,
                    headerAndFooterHtmlUrl, 1024, 0);
            headerHtml.FitHeight = true;
            pdfConverter.PdfHeaderOptions.AddElement(headerHtml);
        }
Beispiel #29
0
        public void AddHeaderElements(PdfConverter pdfConverter, string htmlFooter)
        {
            pdfConverter.PdfDocumentOptions.LeftMargin   = 30;
            pdfConverter.PdfDocumentOptions.RightMargin  = 30;
            pdfConverter.PdfDocumentOptions.TopMargin    = 30;
            pdfConverter.PdfDocumentOptions.BottomMargin = 30;

            // handle the PrepareRenderPdfPageEvent to set the header and footer visibility on different pages
            pdfConverter.PrepareRenderPdfPageEvent += new PrepareRenderPdfPageDelegate(pdfConverter_PrepareRenderPdfPageEvent);

            pdfConverter.PdfDocumentOptions.ShowHeader = true;
            pdfConverter.PdfDocumentOptions.ShowFooter = true;
            pdfConverter.PdfHeaderOptions.HeaderHeight = 50;
            pdfConverter.PdfFooterOptions.FooterHeight = 60;

            // Logo linksBoven
            HtmlToPdfElement HtmlLogo = new HtmlToPdfElement(5, 0, 0, 0,
                                                             "<img alt=\"\" src=\"http://www.zeebregts.nl/images/logo.png\" style=\"margin-bottom:15px\"/>", null, 1024, 0);

            HtmlLogo.FitHeight  = true;
            HtmlLogo.EmbedFonts = true;
            pdfConverter.PdfHeaderOptions.AddElement(HtmlLogo);

            // Aantal Pagina's Rechtsboven
            TextElement HeaderText = new TextElement(0, 10, "&p; van &P;  ", new System.Drawing.Font((new System.Drawing.FontFamily("Calibri")), 8, System.Drawing.GraphicsUnit.Point)); //x

            HeaderText.EmbedSysFont = true;
            HeaderText.TextAlign    = HorizontalTextAlign.Right;
            //HeaderText.TextFont.Size = 10;
            pdfConverter.PdfHeaderOptions.AddElement(HeaderText);

            // Footer rechtsonder (Alleen op eerste pagina)
            //if (pdfConverter.PdfDocumentOptions.w

            // Dit is echt debiel, maar ik moet gewoon handmatig de breedte aanpassen bij Landscape !!!
            if (pdfConverter.PdfDocumentOptions.PdfPageOrientation == PdfPageOrientation.Landscape)
            {
                htmlFooter = htmlFooter.Replace("100%", "36.2cm");
            }
            HtmlToPdfElement HtmlFooter = new HtmlToPdfElement(0, 0, 0, 0, htmlFooter, null, 1024, 0);

            //HtmlToPdfElement HtmlFooter = new HtmlToPdfElement(htmlFooter);
            HtmlFooter.FitHeight    = true;
            HtmlFooter.EmbedFonts   = true;
            HtmlFooter.FitWidth     = true;
            HtmlFooter.StretchToFit = true;
            pdfConverter.PdfFooterOptions.AddElement(HtmlFooter);
        }
Beispiel #30
0
        /// <summary>
        /// Draw the alternative page footer elements
        /// </summary>
        /// <param name="htmlToPdfConverter">The HTML to PDF Converter object</param>
        /// <param name="addPageNumbers">A flag indicating if the page numbering is present in footer</param>
        /// <param name="drawFooterLine">A flag indicating if a line should be drawn at the top of the footer</param>
        private void DrawAlternativePageFooter(Template footerTemplate, bool addPageNumbers, bool drawFooterLine)
        {
            string footerHtmlUrl = Server.MapPath("~/DemoAppFiles/Input/HTML_Files/Footer_Alt_HTML.html");

            // Create a HTML element to be added in footer
            HtmlToPdfElement footerHtml = new HtmlToPdfElement(footerHtmlUrl);

            // Set the HTML element to fit the container height
            footerHtml.FitHeight = true;

            // Add HTML element to footer
            footerTemplate.AddElement(footerHtml);

            // Add page numbering
            if (addPageNumbers)
            {
                // Create a text element with page numbering place holders &p; and & P;
                TextElement footerText = new TextElement(10, 30, "Page &p; of &P;",
                                                         new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 10, System.Drawing.GraphicsUnit.Point));

                // Align the text at the right of the footer
                footerText.TextAlign = HorizontalTextAlign.Left;

                // Set page numbering text color
                footerText.ForeColor = Color.Navy;

                // Embed the text element font in PDF
                footerText.EmbedSysFont = true;

                // Add the text element to footer
                footerTemplate.AddElement(footerText);
            }

            if (drawFooterLine)
            {
                float footerWidth = footerTemplate.Width;

                // Create a line element for the top of the footer
                LineElement footerLine = new LineElement(0, 0, footerWidth, 0);

                // Set line color
                footerLine.ForeColor = Color.Gray;

                // Add line element to the bottom of the footer
                footerTemplate.AddElement(footerLine);
            }
        }
        private void AddHtmlFooter(Document document, PdfFont footerPageNumberFont)
        {
            string headerAndFooterHtmlUrl = Path.Combine(Application.StartupPath, @"..\..\HeaderFooter\HeaderAndFooterHtml.htm");

            //create a template to be added in the header and footer
            document.Footer = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 60);
            // create a HTML to PDF converter element to be added to the header template
            HtmlToPdfElement footerHtmlToPdf = new HtmlToPdfElement(0, 0, document.Footer.ClientRectangle.Width,
                    document.Footer.ClientRectangle.Height, headerAndFooterHtmlUrl);
            footerHtmlToPdf.FitHeight = true;
            document.Footer.AddElement(footerHtmlToPdf);

            // add page number to the footer
            TextElement pageNumberText = new TextElement(document.Footer.ClientRectangle.Width - 100, 30,
                                "This is page &p; of &P; pages", footerPageNumberFont);
            document.Footer.AddElement(pageNumberText);
        }
Beispiel #32
0
        private void AddHtmlFooter(Document document, PdfFont footerPageNumberFont)
        {
            string headerAndFooterHtmlUrl = @"HeaderAndFooterHtml.htm";

            //create a template to be added in the header and footer
            document.FooterTemplate = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 100);
            // create a HTML to PDF converter element to be added to the header template
            HtmlToPdfElement footerHtmlToPdf = new HtmlToPdfElement(headerAndFooterHtmlUrl);

            document.FooterTemplate.AddElement(footerHtmlToPdf);

            // add page number to the footer
            TextElement pageNumberText = new TextElement(document.FooterTemplate.ClientRectangle.Width - 100, 30,
                                                         "This is page &p; of &P; pages", footerPageNumberFont);

            document.FooterTemplate.AddElement(pageNumberText);
        }
Beispiel #33
0
        /// <summary>
        /// Draw the header elements
        /// </summary>
        /// <param name="htmlToPdfConverter">The HTML to PDF Converter object</param>
        /// <param name="drawHeaderLine">A flag indicating if a line should be drawn at the bottom of the header</param>
        private void DrawHeader(HtmlToPdfConverter htmlToPdfConverter, bool drawHeaderLine)
        {
            string headerHtmlString = System.IO.File.ReadAllText(Server.MapPath("~/DemoAppFiles/Input/HTML_Files/Header_HTML.html"));
            string headerBaseUrl    = "http://www.evopdf.com/demo/DemoAppFiles/Input/HTML_Files/";

            // Set the header height in points
            htmlToPdfConverter.PdfHeaderOptions.HeaderHeight = 60;

            // Set header background color
            htmlToPdfConverter.PdfHeaderOptions.HeaderBackColor = RgbColor.White;

            // Create a HTML element to be added in header
            HtmlToPdfElement headerHtml = new HtmlToPdfElement(headerHtmlString, headerBaseUrl);

            // Set the HTML element to fit the container height
            headerHtml.FitHeight = true;

            // Add HTML element to header
            htmlToPdfConverter.PdfHeaderOptions.AddElement(headerHtml);

            if (drawHeaderLine)
            {
                // Calculate the header width based on PDF page size and margins
                float headerWidth = htmlToPdfConverter.PdfDocumentOptions.PdfPageSize.Width -
                                    htmlToPdfConverter.PdfDocumentOptions.LeftMargin - htmlToPdfConverter.PdfDocumentOptions.RightMargin;

                // Calculate header height
                float headerHeight = htmlToPdfConverter.PdfHeaderOptions.HeaderHeight;

                // Create a line element for the bottom of the header
                LineElement headerLine = new LineElement(0, headerHeight - 1, headerWidth, headerHeight - 1);

                // Set line color
                headerLine.ForeColor = RgbColor.Gray;

                // Add line element to the bottom of the header
                htmlToPdfConverter.PdfHeaderOptions.AddElement(headerLine);
            }

            // set header visibility in PDF pages
            htmlToPdfConverter.PdfHeaderOptions.ShowInFirstPage = showHeaderInFirstPageCheckBox.Checked;
            htmlToPdfConverter.PdfHeaderOptions.ShowInOddPages  = showHeaderInOddPagesCheckBox.Checked;
            htmlToPdfConverter.PdfHeaderOptions.ShowInEvenPages = showHeaderInEvenPagesCheckBox.Checked;
        }
        private void AddFooter(PdfConverter pdfConverter)
        {
            string headerAndFooterHtmlUrl = System.IO.Path.Combine(Application.StartupPath,
                        @"..\..\HeaderFooter\HeaderAndFooterHtml.htm");

            //enable footer
            pdfConverter.PdfDocumentOptions.ShowFooter = true;
            // set the footer height in points
            pdfConverter.PdfFooterOptions.FooterHeight = 60;
            //write the page number
            TextElement footerText = new TextElement(0, 30, "This is page &p; of &P;  ",
                new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 10, System.Drawing.GraphicsUnit.Point));
            footerText.EmbedSysFont = true;
            footerText.TextAlign = HorizontalTextAlign.Right;
            pdfConverter.PdfFooterOptions.AddElement(footerText);

            // set the footer HTML area
            HtmlToPdfElement footerHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfFooterOptions.FooterHeight,
                    headerAndFooterHtmlUrl, 1024, 0);
            footerHtml.FitHeight = true;
            pdfConverter.PdfFooterOptions.AddElement(footerHtml);
        }
Beispiel #35
0
        private static void AddHeaderElements(PdfConverter pdfConverter)
        {
            // set the header HTML area
            var headerHtml = new HtmlToPdfElement("<img src='img/tdb_logo_l2.png' />", "http://www.thedrillbook.com/")
            {
                FitHeight = true
            };
            pdfConverter.PdfHeaderOptions.AddElement(headerHtml);

            // set the header line
            float pdfPageWidth = pdfConverter.PdfDocumentOptions.PdfPageOrientation == PdfPageOrientation.Portrait ? pdfConverter.PdfDocumentOptions.PdfPageSize.Width : pdfConverter.PdfDocumentOptions.PdfPageSize.Height;

            var headerLine = new LineElement(0, pdfConverter.PdfHeaderOptions.HeaderHeight,
                        pdfPageWidth - pdfConverter.PdfDocumentOptions.LeftMargin - pdfConverter.PdfDocumentOptions.RightMargin,
                        pdfConverter.PdfHeaderOptions.HeaderHeight)
            {
                LineStyle = { LineWidth = 0.5f },
                ForeColor = Color.Black
            };

            pdfConverter.PdfHeaderOptions.AddElement(headerLine);
        }
Beispiel #36
0
        /// <summary>
        /// Draw the document header elements
        /// </summary>
        /// <param name="htmlToPdfConverter">The HTML to PDF Converter object</param>
        /// <param name="drawHeaderLine">A flag indicating if a line should be drawn at the bottom of the header</param>
        private void DrawHeader(HtmlToPdfConverter htmlToPdfConverter, bool drawHeaderLine)
        {
            string headerHtmlUrl = Server.MapPath("~/DemoAppFiles/Input/HTML_Files/Header_HTML.html");

            // Set the header height in points
            htmlToPdfConverter.PdfHeaderOptions.HeaderHeight = 60;

            // Set header background color
            htmlToPdfConverter.PdfHeaderOptions.HeaderBackColor = Color.White;

            // Create a HTML 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 header
            htmlToPdfConverter.PdfHeaderOptions.AddElement(headerHtml);

            if (drawHeaderLine)
            {
                // Calculate the header width based on PDF page size and margins
                float headerWidth = htmlToPdfConverter.PdfDocumentOptions.PdfPageSize.Width -
                                    htmlToPdfConverter.PdfDocumentOptions.LeftMargin - htmlToPdfConverter.PdfDocumentOptions.RightMargin;

                // Calculate header height
                float headerHeight = htmlToPdfConverter.PdfHeaderOptions.HeaderHeight;

                // Create a line element for the bottom of the header
                LineElement headerLine = new LineElement(0, headerHeight - 1, headerWidth, headerHeight - 1);

                // Set line color
                headerLine.ForeColor = Color.Gray;

                // Add line element to the bottom of the header
                htmlToPdfConverter.PdfHeaderOptions.AddElement(headerLine);
            }
        }
Beispiel #37
0
        private void AddFooter(PdfConverter pdfConverter)
        {
            string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri;
            string headerAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HeaderFooter/HeaderAndFooterHtml.htm";

            //enable footer
            pdfConverter.PdfDocumentOptions.ShowFooter = true;
            // set the footer height in points
            pdfConverter.PdfFooterOptions.FooterHeight = 60;
            //write the page number
            TextElement footerText = new TextElement(0, 30, "This is page &p; of &P;  ",
                new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 10, System.Drawing.GraphicsUnit.Point));
            footerText.EmbedSysFont = true;
            footerText.TextAlign = HorizontalTextAlign.Right;
            pdfConverter.PdfFooterOptions.AddElement(footerText);

            // set the footer HTML area
            HtmlToPdfElement footerHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfFooterOptions.FooterHeight,
                    headerAndFooterHtmlUrl, 1024, 0);
            footerHtml.FitHeight = true;
            footerHtml.EmbedFonts = cbEmbedFonts.Checked;
            pdfConverter.PdfFooterOptions.AddElement(footerHtml);
        }
Beispiel #38
0
        public static void WriteHtmlToPdf(string html, Stream outputStream)
        {
            LicensingManager.LicenseKey = LicenseKey;
            var document = new Document();

            document.CompressionLevel = CompressionLevel.NormalCompression;
            document.Margins = new Margins();
            document.Security.CanPrint = true;
            document.Security.UserPassword = "";

            document.DocumentInformation.Author = "MvcSolution";
            document.ViewerPreferences.HideToolbar = false;

            var page = document.Pages.AddNewPage(PageSize.A4, new Margins(25, 25, 25, 25), PageOrientation.Portrait);

            var smallfont = document.Fonts.Add(new Font(new FontFamily("Verdana"), 9, GraphicsUnit.Point));

            document.FooterTemplate = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 60);

            document.FooterTemplate.AddElement(new TextElement(document.FooterTemplate.ClientRectangle.Width - 75, 40,
                 "Page &p; of &P;", smallfont));

            var htmlDoc = new HtmlToPdfElement(0, 0, -1, html, string.Empty, 700);

            htmlDoc.FitWidth = true;
            htmlDoc.EmbedFonts = true;
            htmlDoc.LiveUrlsEnabled = false;

            htmlDoc.ScriptsEnabled = false;
            htmlDoc.ActiveXEnabled = false;

            // add the HTML to PDF converter element to the page

            page.AddElement(htmlDoc);
            document.Save(outputStream);
        }
        private void btnConvert_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            try
            {
                PdfConverter pdfConverter = new PdfConverter();

                // set the license key
                pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE=";

                // show header and footer in the rendered PDF
                pdfConverter.PdfDocumentOptions.ShowHeader = true;
                pdfConverter.PdfDocumentOptions.ShowFooter = true;

                // set the header height in points
                pdfConverter.PdfHeaderOptions.HeaderHeight = 60;

                // set the header HTML area
                HtmlToPdfElement headerHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfHeaderOptions.HeaderHeight,
                    Path.Combine(Application.StartupPath, @"..\..\HeaderFooter\HeaderAndFooterHtml.htm"), 1024, 0);
                headerHtml.FitHeight = true;
                pdfConverter.PdfHeaderOptions.AddElement(headerHtml);

                // set the footer height in points
                pdfConverter.PdfFooterOptions.FooterHeight = 60;
                //write the page number
                TextElement footerTextElement = new TextElement(0, 30, "This is page &p; of &P;  ",
                    new Font(new FontFamily("Times New Roman"), 10, GraphicsUnit.Point));
                footerTextElement.TextAlign = HorizontalTextAlign.Right;
                pdfConverter.PdfFooterOptions.AddElement(footerTextElement);

                // set the footer HTML area
                HtmlToPdfElement footerHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfFooterOptions.FooterHeight,
                    Path.Combine(Application.StartupPath, @"..\..\HeaderFooter\HeaderAndFooterHtml.htm"), 1024, 0);
                footerHtml.FitHeight = true;
                pdfConverter.PdfFooterOptions.AddElement(footerHtml);

                // save the PDF bytes in a file on disk
                string outFilePath = Path.Combine(Application.StartupPath, "HtmlInHeaderAndFooter.pdf");

                if (!cbAlternateHeaderAndFooter.Checked)
                {
                    // the header content is the same on all the PDF pages
                    // the footer content is the same on all the PDF pages
                    pdfConverter.SavePdfFromUrlToFile(textBoxURL1.Text, outFilePath);
                }
                else
                {
                    // set an alternate header and footer on the even pages

                    // call the converter and get a Document object from URL
                    Document pdfDocument = pdfConverter.GetPdfDocumentObjectFromUrl(textBoxURL1.Text);

                    if (pdfDocument.Pages.Count >= 2)
                    {
                        // get the alternate header and footer width and height
                        // the width is given by the PDF page width
                        float altHeaderFooterWidth = pdfDocument.Pages[0].ClientRectangle.Width;
                        // the height is the same with the document header height from the PdfConverter object
                        float altHeaderHeight = pdfConverter.PdfHeaderOptions.HeaderHeight;
                        float altFooterHeight = pdfConverter.PdfFooterOptions.FooterHeight;

                        // create the alternate header template
                        Template altHeaderTemplate = pdfDocument.Templates.AddNewTemplate(altHeaderFooterWidth, altHeaderHeight);

                        // add html to the header
                        HtmlToPdfElement altHeaderHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfHeaderOptions.HeaderHeight,
                            Path.Combine(Application.StartupPath, @"..\..\HeaderFooter\HeaderAndFooterHtml2.htm"), 1024, 0);
                        altHeaderHtml.FitHeight = true;
                        altHeaderTemplate.AddElement(altHeaderHtml);

                        // add a horizontal line to the bottom of the header
                        LineElement headerLine = new LineElement(0, altHeaderHeight, altHeaderFooterWidth, altHeaderHeight);
                        altHeaderTemplate.AddElement(headerLine);

                        // add page numbering to the left of the header
                        PdfFont pageNumberFont = pdfDocument.Fonts.Add(new Font(new FontFamily("Times New Roman"), 10, GraphicsUnit.Point));
                        TextElement pageNumbering = new TextElement(10, 10, "Page &p; of &P;", pageNumberFont, Color.Blue);

                        altHeaderTemplate.AddElement(pageNumbering);

                        // create the alternate footer template
                        Template altFooterTemplate = pdfDocument.Templates.AddNewTemplate(altHeaderFooterWidth, altFooterHeight);

                        // add html to the footer
                        HtmlToPdfElement altFooterHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfHeaderOptions.HeaderHeight,
                            Path.Combine(Application.StartupPath, @"..\..\HeaderFooter\HeaderAndFooterHtml2.htm"), 1024, 0);
                        altFooterHtml.FitHeight = true;
                        altFooterTemplate.AddElement(altFooterHtml);

                        for (int pageIndex = 1; pageIndex < pdfDocument.Pages.Count; pageIndex += 2)
                        {
                            PdfPage pdfPage = pdfDocument.Pages[pageIndex];

                            pdfPage.Header = altHeaderTemplate;
                            pdfPage.Footer = altFooterTemplate;
                        }
                    }

                    // save the PDF document to a file on disk
                    try
                    {
                        pdfDocument.Save(outFilePath);
                    }
                    finally
                    {
                        // close the Document to realease all the resources
                        pdfDocument.Close();
                    }
                }

                DialogResult dr = MessageBox.Show("Open the rendered file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo);
                if (dr == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(outFilePath);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }
        }
Beispiel #40
0
        /// <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 btnConvert_Click(object sender, EventArgs e)
        {
            PdfConverter pdfConverter = new PdfConverter();

            // set the license key - required
            pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE=";

            // add header and footer
            if (cbAddHeader.Checked)
                AddHeader(pdfConverter);
            if (cbAddFooter.Checked)
                AddFooter(pdfConverter);

            // call the converter and get a Document object from URL
            Document pdfDocument = pdfConverter.GetPdfDocumentObjectFromUrl(textBoxURL1.Text.Trim());

            // get the conversion summary object from the event arguments
            ConversionSummary conversionSummary = pdfConverter.ConversionSummary;

            // the PDF page where the previous conversion ended
            PdfPage lastPage = pdfDocument.Pages[conversionSummary.LastPageIndex];
            // the last rectangle in the last PDF page where the previous conversion ended
            RectangleF lastRectangle = conversionSummary.LastPageRectangle;

            // the result of adding an element to a PDF page
            // ofers the index of the PDF page where the rendering ended
            // and the bounding rectangle of the rendered content in the last page
            AddElementResult addResult = null;

            // the converter for the second URL
            HtmlToPdfElement htmlToPdfURL2 = null;

            if (cbStartOnNewPage.Checked)
            {
                // render the HTML from the second URL on a new page after the first URL
                PdfPage newPage = pdfDocument.Pages.AddNewPage();
                htmlToPdfURL2 = new HtmlToPdfElement(0, 0, textBoxURL2.Text);
                addResult = newPage.AddElement(htmlToPdfURL2);
            }
            else
            {
                // render the HTML from the second URL immediately after the first URL
                htmlToPdfURL2 = new HtmlToPdfElement(lastRectangle.Left, lastRectangle.Bottom, textBoxURL2.Text);
                addResult = lastPage.AddElement(htmlToPdfURL2);
            }

            // the PDF page where the previous conversion ended
            lastPage = pdfDocument.Pages[addResult.EndPageIndex];

            // add a HTML string after all the rendered content
            HtmlToPdfElement htmlStringToPdf = new HtmlToPdfElement(addResult.EndPageBounds.Left, addResult.EndPageBounds.Bottom,
                "<b><i>The rendered content ends here</i></b>", null);

            lastPage.AddElement(htmlStringToPdf);

            byte[] pdfBytes = null;

            try
            {
                pdfBytes = pdfDocument.Save();
            }
            finally
            {
                // close the Document to realease all the resources
                pdfDocument.Close();
            }

            // send the generated PDF document to client browser

            // get the object representing the HTTP response to browser
            HttpResponse httpResponse = HttpContext.Current.Response;

            // add the Content-Type and Content-Disposition HTTP headers
            httpResponse.AddHeader("Content-Type", "application/pdf");
            httpResponse.AddHeader("Content-Disposition", String.Format("attachment; filename=ConvertMultipleUrls.pdf; size={0}", pdfBytes.Length.ToString()));

            // write the PDF document bytes as attachment to HTTP response
            httpResponse.BinaryWrite(pdfBytes);

            // Note: it is important to end the response, otherwise the ASP.NET
            // web page will render its content to PDF document stream
            httpResponse.End();
        }
        private void btnConvert_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            try
            {
                PdfConverter pdfConverter = new PdfConverter();

                // set the license key
                pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE=";

                // add header and footer
                if (cbAddHeader.Checked)
                    AddHeader(pdfConverter);
                if (cbAddFooter.Checked)
                    AddFooter(pdfConverter);

                // call the converter and get a Document object from URL
                Document pdfDocument = pdfConverter.GetPdfDocumentObjectFromUrl(textBoxURL1.Text.Trim());

                // get the conversion summary object from the event arguments
                ConversionSummary conversionSummary = pdfConverter.ConversionSummary;

                // the PDF page where the previous conversion ended
                PdfPage lastPage = pdfDocument.Pages[conversionSummary.LastPageIndex];
                // the last rectangle in the last PDF page where the previous conversion ended
                RectangleF lastRectangle = conversionSummary.LastPageRectangle;

                // the result of adding an element to a PDF page
                // ofers the index of the PDF page where the rendering ended
                // and the bounding rectangle of the rendered content in the last page
                AddElementResult addResult = null;

                // the converter for the second URL
                HtmlToPdfElement htmlToPdfURL2 = null;

                if (cbStartOnNewPage.Checked)
                {
                    // render the HTML from the second URL on a new page after the first URL
                    PdfPage newPage = pdfDocument.Pages.AddNewPage();
                    htmlToPdfURL2 = new HtmlToPdfElement(0, 0, textBoxURL2.Text);
                    addResult = newPage.AddElement(htmlToPdfURL2);
                }
                else
                {
                    // render the HTML from the second URL immediately after the first URL
                    htmlToPdfURL2 = new HtmlToPdfElement(lastRectangle.Left, lastRectangle.Bottom, textBoxURL2.Text);
                    addResult = lastPage.AddElement(htmlToPdfURL2);
                }

                // the PDF page where the previous conversion ended
                lastPage = pdfDocument.Pages[addResult.EndPageIndex];

                // add a HTML string after all the rendered content
                HtmlToPdfElement htmlStringToPdf = new HtmlToPdfElement(addResult.EndPageBounds.Left, addResult.EndPageBounds.Bottom,
                    "<b><i>The rendered content ends here</i></b>", null);

                lastPage.AddElement(htmlStringToPdf);

                // save the PDF bytes in a file on disk
                string outFilePath = System.IO.Path.Combine(Application.StartupPath, "Result.pdf");

                // save the PDF document to a file on disk
                try
                {
                    pdfDocument.Save(outFilePath);
                }
                finally
                {
                    // close the Document to realease all the resources
                    pdfDocument.Close();
                }

                // open the generated PDF document in an external viewer
                DialogResult dr = MessageBox.Show("Open the rendered file in an external viewer?",
                    "Open Rendered File", MessageBoxButtons.YesNo);

                if (dr == DialogResult.Yes)
                {
                    System.Diagnostics.Process.Start(outFilePath);
                }
            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            finally
            {
                this.Cursor = Cursors.Arrow;
            }
        }
Beispiel #43
0
        private void AddHeader(PdfConverter pdfConverter)
        {
            string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri;
            string headerAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HeaderFooter/HeaderAndFooterHtml.htm";

            //enable header
            pdfConverter.PdfDocumentOptions.ShowHeader = true;
            // set the header height in points
            pdfConverter.PdfHeaderOptions.HeaderHeight = 60;
            // set the header HTML area
            HtmlToPdfElement headerHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfHeaderOptions.HeaderHeight,
                    headerAndFooterHtmlUrl, 1024, 0);
            headerHtml.FitHeight = true;
            headerHtml.EmbedFonts = cbEmbedFonts.Checked;
            pdfConverter.PdfHeaderOptions.AddElement(headerHtml);
        }
    private void CreateFactSheetPDF(string factSheetHTML)
    {
        //set the license key
        LicensingManager.LicenseKey = ConfigurationManager.AppSettings["PDFConverterLicense"].ToString();

        //create a PDF document
        Document document = new Document();

        document.CompressionLevel = CompressionLevel.NoCompression;
        document.Margins = new Margins(15, 10, 0, 0);
        document.Security.CanPrint = true;
        document.DocumentInformation.Author = _authorName;
        document.ViewerPreferences.HideToolbar = false;

        //Add a first page to the document. The next pages will inherit the settings from this page
        PdfPage page = document.Pages.AddNewPage(PageSize.A4, new Margins(10, 10, 0, 0), PageOrientation.Landscape);
        PdfFont font = document.Fonts.Add(new System.Drawing.Font(new System.Drawing.FontFamily("Arial"), 10, System.Drawing.GraphicsUnit.Point));
        font = document.Fonts.Add(new System.Drawing.Font(new System.Drawing.FontFamily("Arial"), 10, System.Drawing.GraphicsUnit.Point));
        font = document.Fonts.Add(new System.Drawing.Font(new System.Drawing.FontFamily("Arial"), 10, System.Drawing.GraphicsUnit.Point));

        HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement(factSheetHTML, _URLToConvert);
        htmlToPdfElement.TruncateOutOfBoundsText = false;
        htmlToPdfElement.FitWidth = true;
        htmlToPdfElement.StretchToFit = true;
        htmlToPdfElement.HtmlViewerHeight = 0;
        htmlToPdfElement.HtmlViewerWidth = 950;
        htmlToPdfElement.AvoidImageBreak = true;
        htmlToPdfElement.EmbedFonts = true;
        htmlToPdfElement.ScriptsEnabled = true;

        // the result of adding an element to a PDF page
        AddElementResult addResult;
        addResult = page.AddElement(htmlToPdfElement);

        try
        {
            document.Save(Response, true, _pdfFileName);
        }
        finally
        {
            // close the PDF document to release the resources
            document.Close();
        }
    }
Beispiel #45
0
    private void AddSummaryFooter(PdfConverter pdfConverter, string contentPath, SummaryReportHeaderType reportHeaderType)
    {
        //enable footer
        pdfConverter.PdfDocumentOptions.ShowFooter = true;
        pdfConverter.PdfFooterOptions.FooterHeight = 85;

        var url = "/templates/SummaryFooter.htm";

        if (reportHeaderType == SummaryReportHeaderType.NI)
        {
            url = "/templates/SummaryFooterNI.htm";
        }
        else if (reportHeaderType == SummaryReportHeaderType.ROI)
        {
           url = "/templates/SummaryFooterROI.htm";
        }

        //write the footer
        var summaryFooterUrl = contentPath + url;
        var footerHtml = new HtmlToPdfElement(0, 5, 0, pdfConverter.PdfFooterOptions.FooterHeight, summaryFooterUrl, 1024, 0);

        footerHtml.FitHeight = true;
        pdfConverter.PdfFooterOptions.AddElement(footerHtml);
    }
        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();
        }
Beispiel #47
0
        PdfConverter getPdfConverter(int timeoutInSeconds, Dictionary<string, object> pdfDocumentOptions)
        {
            var pdf = new PdfConverter();

            var cookies = CookieHelper.GetApplicationCookies(ExecutingContext.CurrentApplicationName);

            pdf.LicenseKey = EvoLicense;

            pdf.InterruptSlowJavaScript = false;
            pdf.JavaScriptEnabled = true;

            pdf.ConversionDelay = timeoutInSeconds;

            if(timeoutInSeconds != 0)
              pdf.TriggeringMode = TriggeringMode.Manual;

            pdf.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;          

            var evoInternalDat = String.Format(@"{0}\Applications\EvoHtmlToPdf\Lib\evointernal.dat", Context.HostHome);

            if (!System.IO.File.Exists(evoInternalDat)) {

                var evoDir = Path.GetDirectoryName(evoInternalDat);

                if (!Directory.Exists(evoDir)) Directory.CreateDirectory(evoDir);

                var bytes = InMemoryFileSystem.GetFileBytes(evoInternalDat, true);

                File.WriteAllBytes(evoInternalDat, bytes);
            }

            if (pdfDocumentOptions != null && pdfDocumentOptions.Count > 0)
            {
                var flags = System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.DeclaredOnly;

                var properties = pdf.PdfDocumentOptions.GetType().GetProperties(flags);

                var list = new List<string>();

                foreach (var p in properties)
                {
                    if (pdfDocumentOptions.ContainsKey(p.Name))
                    {
                        p.SetValue(pdf.PdfDocumentOptions, pdfDocumentOptions[p.Name], null);
                    }
                }

                if (pdfDocumentOptions.ContainsKey(HeaderHtml))
                {
                    var headerHtml = new HtmlToPdfElement(pdfDocumentOptions[HeaderHtml].ToString(), "");
                    headerHtml.EvoInternalFileName = evoInternalDat;
                    pdf.PdfHeaderOptions.AddElement(headerHtml);
                }

                if (pdfDocumentOptions.ContainsKey(HeaderHeight)) {
                    pdf.PdfHeaderOptions.HeaderHeight = (float)pdfDocumentOptions[HeaderHeight];
                }

                if (pdfDocumentOptions.ContainsKey(FooterHtml))
                {
                    var footerHtml = new HtmlToPdfElement(pdfDocumentOptions[FooterHtml].ToString(), "");
                    footerHtml.EvoInternalFileName = evoInternalDat; 
                    pdf.PdfFooterOptions.AddElement(footerHtml);
                }

                if (pdfDocumentOptions.ContainsKey(FooterHeight)) {
                    pdf.PdfFooterOptions.FooterHeight = (float)pdfDocumentOptions[FooterHeight];
                }
            }

            //var pageNumbers = new HtmlToPdfVariableElement("<p style = 'text-align:right;'>page &p; of &P;</p>", null);
            //pageNumbers.FitHeight = true;
            //pageNumbers.EvoInternalFileName = evoInternalDat; // code necessaire et qui manquait !!

            //pdf.PdfFooterOptions.FooterHeight = 50;
            //pdf.PdfFooterOptions.AddElement(pageNumbers);

            //var fWidth = pdf.PdfDocumentOptions.PdfPageSize.Width - pdf.PdfDocumentOptions.LeftMargin - pdf.PdfDocumentOptions.RightMargin;

            //LineElement fLine = new LineElement(0, 0, fWidth, 0);
            //fLine.ForeColor = new PdfColor(255, 0, 0);

            //pdf.PdfFooterOptions.AddElement(fLine);

            //var footerHtml = new HtmlToPdfElement(0, 0, 0, pdf.PdfFooterOptions.FooterHeight, "<i>HTML in Footer</i>", null, 1024, 0);
            //footerHtml.FitHeight = true;
            //footerHtml.EmbedFonts = true;
            //footerHtml.EvoInternalFileName = evoInternalDat; // code necessaire et qui manquait !!

            //pdf.PdfFooterOptions.AddElement(footerHtml);

            //pdf.PdfDocumentOptions.ShowFooter = true;
            //pdf.PdfDocumentOptions.BottomMargin = 100;
            //pdf.PdfDocumentOptions.TopMargin = 100;

            pdf.EvoInternalFileName = evoInternalDat;

            foreach (var kv in cookies)
            {
                pdf.HttpRequestCookies.Add(kv.Key, kv.Value.ToString());
            }

            return pdf;
        }
        private void btnConvert_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            string outFilePath = Path.Combine(Application.StartupPath, "HtmlToPdfElement.pdf");

            // the PDF document
            Document document = null;

            try
            {
                //create a PDF document
                document = new Document();

                // set the license key
                document.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE=";

                //optional settings for the PDF document like margins, compression level,
                //security options, viewer preferences, document information, etc
                document.CompressionLevel = PdfCompressionLevel.Normal;
                document.Margins = new Margins(10, 10, 0, 0);
                //document.Security.CanPrint = true;
                //document.Security.UserPassword = "";
                document.DocumentInformation.Author = "HTML to PDF Converter";
                document.ViewerPreferences.HideToolbar = false;

                // set if the JPEG compression is enabled for the images in PDF - default is true
                document.JpegCompressionEnabled = cbJpegCompression.Checked;

                //Add a first page to the document. The next pages will inherit the settings from this page
                PdfPage page = document.Pages.AddNewPage(PdfPageSize.A4, new Margins(10, 10, 0, 0), PdfPageOrientation.Portrait);

                // the code below can be used to create a page with default settings A4, document margins inherited, portrait orientation
                //PdfPage page = document.Pages.AddNewPage();

                // add a font to the document that can be used for the texts elements
                PdfFont font = document.Fonts.Add(new Font(new FontFamily("Times New Roman"), 10, GraphicsUnit.Point));

                // add header and footer before renderng the content
                if (cbAddHeader.Checked)
                    AddHtmlHeader(document);
                if (cbAddFooter.Checked)
                    AddHtmlFooter(document, font);

                // the result of adding an element to a PDF page
                AddElementResult addResult;

                // Get the specified location and size of the rendered content
                // A negative value for width and height means to auto determine
                // The auto determined width is the available width in the PDF page
                // and the auto determined height is the height necessary to render all the content
                float xLocation = float.Parse(textBoxXLocation.Text.Trim());
                float yLocation = float.Parse(textBoxYLocation.Text.Trim());
                float width = float.Parse(textBoxWidth.Text.Trim());
                float height = float.Parse(textBoxHeight.Text.Trim());

                if (radioConvertToSelectablePDF.Checked)
                {
                    // convert HTML to PDF
                    HtmlToPdfElement htmlToPdfElement;

                    // convert a URL to PDF
                    string urlToConvert = textBoxWebPageURL.Text.Trim();

                    htmlToPdfElement = new HtmlToPdfElement(xLocation, yLocation, width, height, urlToConvert);

                    //optional settings for the HTML to PDF converter
                    htmlToPdfElement.FitWidth = cbFitWidth.Checked;
                    htmlToPdfElement.EmbedFonts = cbEmbedFonts.Checked;
                    htmlToPdfElement.LiveUrlsEnabled = cbLiveLinks.Checked;
                    htmlToPdfElement.JavaScriptEnabled = cbScriptsEnabled.Checked;
                    htmlToPdfElement.PdfBookmarkOptions.HtmlElementSelectors = cbBookmarks.Checked ? new string[] { "H1", "H2" } : null;

                    // add theHTML to PDF converter element to page
                    addResult = page.AddElement(htmlToPdfElement);
                }
                else
                {
                    HtmlToImageElement htmlToImageElement;

                    // convert HTML to image and add image to PDF document

                    // convert a URL to PDF
                    string urlToConvert = textBoxWebPageURL.Text.Trim();

                    htmlToImageElement = new HtmlToImageElement(xLocation, yLocation, width, height, urlToConvert);

                    //optional settings for the HTML to PDF converter
                    htmlToImageElement.FitWidth = cbFitWidth.Checked;
                    htmlToImageElement.LiveUrlsEnabled = cbLiveLinks.Checked;
                    htmlToImageElement.JavaScriptEnabled = cbScriptsEnabled.Checked;
                    htmlToImageElement.PdfBookmarkOptions.HtmlElementSelectors = cbBookmarks.Checked ? new string[] { "H1", "H2" } : null;

                    addResult = page.AddElement(htmlToImageElement);
                }

                if (cbAdditionalContent.Checked)
                {
                    // The code below can be used add some other elements right under the conversion result
                    // like texts or another HTML to PDF conversion

                    // add a text element right under the HTML to PDF document
                    PdfPage endPage = document.Pages[addResult.EndPageIndex];
                    TextElement nextTextElement = new TextElement(0, addResult.EndPageBounds.Bottom + 10, "Below there is another HTML to PDF Element", font);
                    nextTextElement.ForeColor = Color.Green;
                    addResult = endPage.AddElement(nextTextElement);

                    // add another HTML to PDF converter element right under the text element
                    endPage = document.Pages[addResult.EndPageIndex];
                    HtmlToPdfElement nextHtmlToPdfElement = new HtmlToPdfElement(0, addResult.EndPageBounds.Bottom + 10, "http://www.google.com");
                    addResult = endPage.AddElement(nextHtmlToPdfElement);
                }

                // save the PDF document to disk
                document.Save(outFilePath);

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
                return;
            }
            finally
            {
                // close the PDF document to release the resources
                if (document != null)
                    document.Close();

                this.Cursor = Cursors.Arrow;
            }

            DialogResult dr = MessageBox.Show("Open the saved file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo);
            if (dr == DialogResult.Yes)
            {
                try
                {
                    System.Diagnostics.Process.Start(outFilePath);
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    return;
                }
            }
        }
        private void AddHtmlFooter(Document document, PdfFont footerPageNumberFont)
        {
            string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri;
            string headerAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HeaderFooter/HeaderAndFooterHtml.htm";

            //create a template to be added in the header and footer
            document.Footer = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 60);
            // create a HTML to PDF converter element to be added to the header template
            HtmlToPdfElement footerHtmlToPdf = new HtmlToPdfElement(0, 0, document.Footer.ClientRectangle.Width,
                    document.Footer.ClientRectangle.Height, headerAndFooterHtmlUrl);
            footerHtmlToPdf.FitHeight = true;
            document.Footer.AddElement(footerHtmlToPdf);

            // add page number to the footer
            TextElement pageNumberText = new TextElement(document.Footer.ClientRectangle.Width - 100, 30,
                                "This is page &p; of &P; pages", footerPageNumberFont);
            document.Footer.AddElement(pageNumberText);
        }
        protected void btnConvert_Click(object sender, EventArgs e)
        {
            //create a PDF document
            Document document = new Document();

            // set the license key
            document.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE=";

            //optional settings for the PDF document like margins, compression level,
            //security options, viewer preferences, document information, etc
            document.CompressionLevel = PdfCompressionLevel.Normal;
            document.Margins = new Margins(10, 10, 0, 0);
            //document.Security.CanPrint = true;
            //document.Security.UserPassword = "";
            document.ViewerPreferences.HideToolbar = false;

            // set if the images are compressed in PDF with JPEG to reduce the PDF document size
            document.JpegCompressionEnabled = cbJpegCompression.Checked;

            //Add a first page to the document. The next pages will inherit the settings from this page
            PdfPage page = document.Pages.AddNewPage(PdfPageSize.A4, new Margins(10, 10, 0, 0), PdfPageOrientation.Portrait);

            // the code below can be used to create a page with default settings A4, document margins inherited, portrait orientation
            //PdfPage page = document.Pages.AddNewPage();

            // add a font to the document that can be used for the texts elements
            PdfFont font = document.Fonts.Add(new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 10,
                        System.Drawing.GraphicsUnit.Point));

            // add header and footer before renderng the content
            if (cbAddHeader.Checked)
                AddHtmlHeader(document);
            if (cbAddFooter.Checked)
                AddHtmlFooter(document, font);

            // the result of adding an element to a PDF page
            AddElementResult addResult;

            // Get the specified location and size of the rendered content
            // A negative value for width and height means to auto determine
            // The auto determined width is the available width in the PDF page
            // and the auto determined height is the height necessary to render all the content
            float xLocation = float.Parse(textBoxXLocation.Text.Trim());
            float yLocation = float.Parse(textBoxYLocation.Text.Trim());
            float width = float.Parse(textBoxWidth.Text.Trim());
            float height = float.Parse(textBoxHeight.Text.Trim());

            if (radioConvertToSelectablePDF.Checked)
            {
                // convert HTML to PDF
                HtmlToPdfElement htmlToPdfElement;

                if (radioConvertURL.Checked)
                {
                    // convert a URL to PDF
                    string urlToConvert = textBoxWebPageURL.Text.Trim();

                    htmlToPdfElement = new HtmlToPdfElement(xLocation, yLocation, width, height, urlToConvert);
                }
                else
                {
                    // convert a HTML string to PDF
                    string htmlStringToConvert = textBoxHTMLCode.Text;
                    string baseURL = textBoxBaseURL.Text.Trim();

                    htmlToPdfElement = new HtmlToPdfElement(xLocation, yLocation, width, height, htmlStringToConvert, baseURL);
                }

                //optional settings for the HTML to PDF converter
                htmlToPdfElement.FitWidth = cbFitWidth.Checked;
                htmlToPdfElement.EmbedFonts = cbEmbedFonts.Checked;
                htmlToPdfElement.LiveUrlsEnabled = cbLiveLinks.Checked;
                htmlToPdfElement.JavaScriptEnabled = cbClientScripts.Checked;
                htmlToPdfElement.PdfBookmarkOptions.HtmlElementSelectors = cbBookmarks.Checked ? new string[] { "H1", "H2" } : null;

                // add theHTML to PDF converter element to page
                addResult = page.AddElement(htmlToPdfElement);
            }
            else
            {
                HtmlToImageElement htmlToImageElement;

                // convert HTML to image and add image to PDF document
                if (radioConvertURL.Checked)
                {
                    // convert a URL to PDF
                    string urlToConvert = textBoxWebPageURL.Text.Trim();

                    htmlToImageElement = new HtmlToImageElement(xLocation, yLocation, width, height, urlToConvert);
                }
                else
                {
                    // convert a HTML string to PDF
                    string htmlStringToConvert = textBoxHTMLCode.Text;
                    string baseURL = textBoxBaseURL.Text.Trim();

                    htmlToImageElement = new HtmlToImageElement(xLocation, yLocation, width, height, htmlStringToConvert, baseURL);
                }

                //optional settings for the HTML to PDF converter
                htmlToImageElement.FitWidth = cbFitWidth.Checked;
                htmlToImageElement.LiveUrlsEnabled = cbLiveLinks.Checked;
                htmlToImageElement.JavaScriptEnabled = cbClientScripts.Checked;
                htmlToImageElement.PdfBookmarkOptions.HtmlElementSelectors = cbBookmarks.Checked ? new string[] { "H1", "H2" } : null;

                addResult = page.AddElement(htmlToImageElement);
            }

            if (cbAdditionalContent.Checked)
            {
                // The code below can be used add some other elements right under the conversion result
                // like texts or another HTML to PDF conversion

                // add a text element right under the HTML to PDF document
                PdfPage endPage = document.Pages[addResult.EndPageIndex];
                TextElement nextTextElement = new TextElement(0, addResult.EndPageBounds.Bottom + 10, "Below there is another HTML to PDF Element", font);
                nextTextElement.ForeColor = System.Drawing.Color.Green;
                addResult = endPage.AddElement(nextTextElement);

                // add another HTML to PDF converter element right under the text element
                endPage = document.Pages[addResult.EndPageIndex];
                HtmlToPdfElement nextHtmlToPdfElement = new HtmlToPdfElement(0, addResult.EndPageBounds.Bottom + 10, "http://www.google.com");
                addResult = endPage.AddElement(nextHtmlToPdfElement);
            }

            try
            {
                // get the PDF document bytes
                byte[] pdfBytes = document.Save();

                // send the generated PDF document to client browser

                // get the object representing the HTTP response to browser
                HttpResponse httpResponse = HttpContext.Current.Response;

                // add the Content-Type and Content-Disposition HTTP headers
                httpResponse.AddHeader("Content-Type", "application/pdf");
                httpResponse.AddHeader("Content-Disposition", String.Format("attachment; filename=HtmlToPdfElement.pdf; size={0}", pdfBytes.Length.ToString()));

                // write the PDF document bytes as attachment to HTTP response
                httpResponse.BinaryWrite(pdfBytes);

                // Note: it is important to end the response, otherwise the ASP.NET
                // web page will render its content to PDF document stream
                httpResponse.End();
            }
            finally
            {
                // close the PDF document to release the resources
                document.Close();
            }
        }
        private void AddHtmlHeader(Document document)
        {
            string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri;
            string headerAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HeaderFooter/HeaderAndFooterHtml.htm";

            //create a template to be added in the header and footer
            document.Header = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 60);
            // create a HTML to PDF converter element to be added to the header template
            HtmlToPdfElement headerHtmlToPdf = new HtmlToPdfElement(0, 0, document.Header.ClientRectangle.Width,
                    document.Header.ClientRectangle.Height, headerAndFooterHtmlUrl);
            headerHtmlToPdf.FitHeight = true;
            document.Header.AddElement(headerHtmlToPdf);
        }
Beispiel #52
0
        public static HtmlToPdfConverter GetInitializedHtmlConverter(string html_string, out string html_body)
        {
            HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter();

            htmlToPdfConverter.PdfDocumentOptions.Width = 750;
            htmlToPdfConverter.HtmlViewerWidth = 650;
            htmlToPdfConverter.PdfDocumentOptions.LeftMargin = 50;
            htmlToPdfConverter.PdfDocumentOptions.RightMargin = 50;
            htmlToPdfConverter.PdfDocumentOptions.TopMargin = 25;
            htmlToPdfConverter.PdfDocumentOptions.BottomMargin = 10;
            htmlToPdfConverter.PdfDocumentOptions.AvoidImageBreak = true;
            htmlToPdfConverter.PdfDocumentOptions.AvoidTextBreak = true;
            htmlToPdfConverter.PdfDocumentOptions.JpegCompressionLevel = 0;

            // Install a handler where to change the header and footer in first page
            htmlToPdfConverter.PrepareRenderPdfPageEvent += new PrepareRenderPdfPageDelegate(htmlToPdfConverter_PrepareRenderPdfPageEvent);

            html_body = "";
            string header = "";
            string footer = "";
            int header_height = 0;
            int footer_height = 0;
            DocumentTemplate.GetPageParts(html_string, out header, out footer, out html_body, out header_height, out footer_height);

            if (!string.IsNullOrEmpty(header))
            {
                htmlToPdfConverter.PdfDocumentOptions.ShowHeader = true;
                htmlToPdfConverter.PdfHeaderOptions.HeaderHeight = header_height;
                HtmlToPdfElement headerElem = new HtmlToPdfElement(0, 0, 0, header, "", 680);
                headerElem.FitHeight = true;
                htmlToPdfConverter.PdfHeaderOptions.AddElement(headerElem);
            }
            if (!string.IsNullOrEmpty(footer))
            {
                htmlToPdfConverter.PdfDocumentOptions.ShowFooter = true;
                HtmlToPdfElement footerElem = new HtmlToPdfElement(footer, "");
                if (footer_height > 0)
                    htmlToPdfConverter.PdfFooterOptions.FooterHeight = footer_height;
                else
                    footerElem.FitHeight = true;
                htmlToPdfConverter.PdfFooterOptions.AddElement(footerElem);
            }

            htmlToPdfConverter.LicenseKey = "sjwvPS4uPSskPSgzLT0uLDMsLzMkJCQk";
            htmlToPdfConverter.PdfDocumentOptions.AvoidImageBreak = true;

            return htmlToPdfConverter;
        }
        ////Send executed command to output window. So, user will know what he executed
        //protected override void SendToOutputWindow(string command, string title)//13Dec2013
        //{
        //    #region Get Active output Window
        //    //////// Active output window ///////
        //    OutputWindowContainer owc = (LifetimeService.Instance.Container.Resolve<IOutputWindowContainer>()) as OutputWindowContainer;
        //    OutputWindow ow = owc.ActiveOutputWindow as OutputWindow; //get currently active window
        //    #endregion
        //    ow.AddMessage(command, title);
        //}
        #region Save HTML as PDF
        private void HTML2PDF(string htmlFilename, string outFilePath) //outFilePath is full path filename of PDF to be generated
        {
            bool addHeader = false, addFooter = false;
            bool createSelecteablePDF = true;
            //this.Cursor = Cursors.WaitCursor;

            //string outFilePath = Path.Combine(Application.StartupPath, "htmltopdf.pdf");

            try
            {
                //set the license key
                //LicensingManager.LicenseKey = "put your license key here";

                //create a PDF document
                Document document = new Document();

                //optional settings for the PDF document like margins, compression level,
                //security options, viewer preferences, document information, etc
                document.CompressionLevel = CompressionLevel.NormalCompression;
                document.Margins = new Margins(10, 10, 0, 0);
                document.Security.CanPrint = true;
                document.Security.UserPassword = "";
                document.DocumentInformation.Author = "HTML to PDF Converter";
                document.ViewerPreferences.HideToolbar = false;

                //Add a first page to the document. The next pages will inherit the settings from this page 
                PdfPage page = document.Pages.AddNewPage(PageSize.A4, new Margins(10, 10, 0, 0), PageOrientation.Portrait);

                // the code below can be used to create a page with default settings A4, document margins inherited, portrait orientation
                //PdfPage page = document.Pages.AddNewPage();

                // add a font to the document that can be used for the texts elements 
                PdfFont font = document.Fonts.Add(new Font(new FontFamily("Times New Roman"), 10, GraphicsUnit.Point));

                // add header and footer before renderng the content
                //if (addHeader)
                //    AddHtmlHeader(document);
                //if (addFooter)
                //    AddHtmlFooter(document, font);

                // the result of adding an element to a PDF page
                AddElementResult addResult;

                // Get the specified location and size of the rendered content
                // A negative value for width and height means to auto determine
                // The auto determined width is the available width in the PDF page
                // and the auto determined height is the height necessary to render all the content
                float xLocation = 0;// float.Parse(textBoxXLocation.Text.Trim());
                float yLocation = 0;// float.Parse(textBoxYLocation.Text.Trim());
                float width = -1;// float.Parse(textBoxWidth.Text.Trim());
                float height = -1;// float.Parse(textBoxHeight.Text.Trim());

                if (createSelecteablePDF)
                {
                    // convert HTML to PDF
                    HtmlToPdfElement htmlToPdfElement;


                    // convert a URL to PDF
                    string urlToConvert = htmlFilename;// textBoxWebPageURL.Text.Trim();

                    htmlToPdfElement = new HtmlToPdfElement(xLocation, yLocation, width, height, urlToConvert);


                    //optional settings for the HTML to PDF converter
                    htmlToPdfElement.FitWidth = true;// cbFitWidth.Checked;
                    htmlToPdfElement.EmbedFonts = false;// cbEmbedFonts.Checked;
                    htmlToPdfElement.LiveUrlsEnabled = false;// cbLiveLinks.Checked;
                    htmlToPdfElement.RightToLeftEnabled = false;// cbRTLEnabled.Checked;
                    htmlToPdfElement.ScriptsEnabled = false;// cbScriptsEnabled.Checked;
                    htmlToPdfElement.ActiveXEnabled = false;// cbActiveXEnabled.Checked;

                    // add theHTML to PDF converter element to page
                    addResult = page.AddElement(htmlToPdfElement);
                }
                else
                {
                    HtmlToImageElement htmlToImageElement;

                    // convert HTML to image and add image to PDF document

                    // convert a URL to PDF
                    string urlToConvert = htmlFilename;// textBoxWebPageURL.Text.Trim();

                    htmlToImageElement = new HtmlToImageElement(xLocation, yLocation, width, height, urlToConvert);

                    //optional settings for the HTML to PDF converter
                    htmlToImageElement.FitWidth = true;// cbFitWidth.Checked;
                    htmlToImageElement.ScriptsEnabled = false;// cbScriptsEnabled.Checked;
                    htmlToImageElement.ActiveXEnabled = false;// cbActiveXEnabled.Checked;

                    addResult = page.AddElement(htmlToImageElement);
                }

                if (false)//cbAdditionalContent.Checked)
                {
                    // The code below can be used add some other elements right under the conversion result 
                    // like texts or another HTML to PDF conversion

                    // add a text element right under the HTML to PDF document
                    PdfPage endPage = document.Pages[addResult.EndPageIndex];
                    TextElement nextTextElement = new TextElement(0, addResult.EndPageBounds.Bottom + 10, "Below there is another HTML to PDF Element", font);
                    nextTextElement.ForeColor = Color.Green;
                    addResult = endPage.AddElement(nextTextElement);

                    // add another HTML to PDF converter element right under the text element
                    endPage = document.Pages[addResult.EndPageIndex];
                    HtmlToPdfElement nextHtmlToPdfElement = new HtmlToPdfElement(0, addResult.EndPageBounds.Bottom + 10, "http://www.google.com");
                    addResult = endPage.AddElement(nextHtmlToPdfElement);
                }

                // save the PDF document to disk
                document.Save(outFilePath);

            }
            finally
            {
                //this.Cursor = Cursors.Arrow;
            }

            //DialogResult dr = MessageBox.Show("Open the saved file in an external viewer?", "Open Rendered File", MessageBoxButtons.YesNo, MessageBoxIcon.Information);
            //if (dr == DialogResult.Yes)
            //{
            //    try
            //    {
            //        System.Diagnostics.Process.Start(outFilePath);
            //    }
            //    catch (Exception ex)
            //    {
            //        MessageBox.Show(ex.Message);
            //        return;
            //    }
            //}
        }
        protected void btnConvert_Click(object sender, EventArgs e)
        {
            PdfConverter pdfConverter = new PdfConverter();

            // set the license key
            pdfConverter.LicenseKey = "B4mYiJubiJiInIaYiJuZhpmahpGRkZE=";

            // show header and footer in the rendered PDF
            pdfConverter.PdfDocumentOptions.ShowHeader = true;
            pdfConverter.PdfDocumentOptions.ShowFooter = true;

            // set the header height in points
            pdfConverter.PdfHeaderOptions.HeaderHeight = 60;

            string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri;
            string headerAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) +
                            "/HeaderFooter/HeaderAndFooterHtml.htm";

            // set the header HTML area
            HtmlToPdfElement headerHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfHeaderOptions.HeaderHeight,
                   headerAndFooterHtmlUrl, 1024, 0);
            headerHtml.FitHeight = true;
            pdfConverter.PdfHeaderOptions.AddElement(headerHtml);

            // set the footer height in points
            pdfConverter.PdfFooterOptions.FooterHeight = 60;
            //write the page number
            TextElement footerTextElement = new TextElement(0, 30, "This is page &p; of &P;  ",
                    new Font(new FontFamily("Times New Roman"), 10, GraphicsUnit.Point));
            footerTextElement.TextAlign = HorizontalTextAlign.Right;
            pdfConverter.PdfFooterOptions.AddElement(footerTextElement);

            // set the footer HTML area
            HtmlToPdfElement footerHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfFooterOptions.FooterHeight,
                headerAndFooterHtmlUrl, 1024, 0);
            footerHtml.FitHeight = true;
            pdfConverter.PdfFooterOptions.AddElement(footerHtml);

            if (!cbAlternateHeaderAndFooter.Checked)
            {
                // Performs the conversion and get the pdf document bytes that can
                // be saved to a file or sent as a browser response
                byte[] pdfBytes = pdfConverter.GetPdfBytesFromUrl(textBoxWebPageURL.Text);

                // send the generated PDF document to client browser

                // get the object representing the HTTP response to browser
                HttpResponse httpResponse = HttpContext.Current.Response;

                // add the Content-Type and Content-Disposition HTTP headers
                httpResponse.AddHeader("Content-Type", "application/pdf");
                httpResponse.AddHeader("Content-Disposition", String.Format("attachment; filename=HtmlInHeaderAndFooter.pdf; size={0}", pdfBytes.Length.ToString()));

                // write the PDF document bytes as attachment to HTTP response
                httpResponse.BinaryWrite(pdfBytes);

                // Note: it is important to end the response, otherwise the ASP.NET
                // web page will render its content to PDF document stream
                httpResponse.End();
            }
            else
            {
                // set an alternate header and footer on the even pages

                // call the converter and get a Document object from URL
                Document pdfDocument = pdfConverter.GetPdfDocumentObjectFromUrl(textBoxWebPageURL.Text);

                if (pdfDocument.Pages.Count >= 2)
                {
                    // get the alternate header and footer width and height
                    // the width is given by the PDF page width
                    float altHeaderFooterWidth = pdfDocument.Pages[0].ClientRectangle.Width;
                    // the height is the same with the document header height from the PdfConverter object
                    float altHeaderHeight = pdfConverter.PdfHeaderOptions.HeaderHeight;
                    float altFooterHeight = pdfConverter.PdfFooterOptions.FooterHeight;

                    // create the alternate header template
                    Template altHeaderTemplate = pdfDocument.Templates.AddNewTemplate(altHeaderFooterWidth, altHeaderHeight);

                    string alternateHeaderAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) +
                                "/HeaderFooter/HeaderAndFooterHtml2.htm";

                    // add html to the header
                    HtmlToPdfElement altHeaderHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfHeaderOptions.HeaderHeight,
                                        alternateHeaderAndFooterHtmlUrl, 1024, 0);
                    altHeaderHtml.FitHeight = true;
                    altHeaderTemplate.AddElement(altHeaderHtml);

                    // add a horizontal line to the bottom of the header
                    LineElement headerLine = new LineElement(0, altHeaderHeight, altHeaderFooterWidth, altHeaderHeight);
                    altHeaderTemplate.AddElement(headerLine);

                    // add page numbering to the left of the header
                    PdfFont pageNumberFont = pdfDocument.Fonts.Add(new Font(new FontFamily("Times New Roman"), 10, GraphicsUnit.Point));
                    TextElement pageNumbering = new TextElement(10, 10, "Page &p; of &P;", pageNumberFont, Color.Blue);

                    altHeaderTemplate.AddElement(pageNumbering);

                    // create the alternate footer template
                    Template altFooterTemplate = pdfDocument.Templates.AddNewTemplate(altHeaderFooterWidth, altFooterHeight);

                    // add html to the footer
                    HtmlToPdfElement altFooterHtml = new HtmlToPdfElement(0, 0, 0, pdfConverter.PdfHeaderOptions.HeaderHeight,
                                        alternateHeaderAndFooterHtmlUrl, 1024, 0);
                    altFooterHtml.FitHeight = true;
                    altFooterTemplate.AddElement(altFooterHtml);

                    for (int pageIndex = 1; pageIndex < pdfDocument.Pages.Count; pageIndex += 2)
                    {
                        PdfPage pdfPage = pdfDocument.Pages[pageIndex];

                        pdfPage.Header = altHeaderTemplate;
                        pdfPage.Footer = altFooterTemplate;
                    }
                }

                byte[] pdfBytes = null;

                try
                {
                    pdfBytes = pdfDocument.Save();
                }
                finally
                {
                    // close the Document to realease all the resources
                    pdfDocument.Close();
                }

                // send the generated PDF document to client browser

                // get the object representing the HTTP response to browser
                HttpResponse httpResponse = HttpContext.Current.Response;

                // add the Content-Type and Content-Disposition HTTP headers
                httpResponse.AddHeader("Content-Type", "application/pdf");
                httpResponse.AddHeader("Content-Disposition", String.Format("attachment; filename=HtmlInHeaderAndFooter.pdf; size={0}", pdfBytes.Length.ToString()));

                // write the PDF document bytes as attachment to HTTP response
                httpResponse.BinaryWrite(pdfBytes);

                // Note: it is important to end the response, otherwise the ASP.NET
                // web page will render its content to PDF document stream
                httpResponse.End();
            }
        }
        private void AddHtmlHeader(Document document)
        {
            string headerAndFooterHtmlUrl =  @"HeaderAndFooterHtml.htm";

            //create a template to be added in the header and footer
            document.HeaderTemplate = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 100);
            // create a HTML to PDF converter element to be added to the header template
            HtmlToPdfElement headerHtmlToPdf = new HtmlToPdfElement(headerAndFooterHtmlUrl);
            document.HeaderTemplate.AddElement(headerHtmlToPdf);
        }
        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();
            }
        }
        private void AddHtmlFooter(Document document, PdfFont footerPageNumberFont)
        {
            string headerAndFooterHtmlUrl = @"HeaderAndFooterHtml.htm";

            //create a template to be added in the header and footer
            document.FooterTemplate = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 100);
            // create a HTML to PDF converter element to be added to the header template
            HtmlToPdfElement footerHtmlToPdf = new HtmlToPdfElement(headerAndFooterHtmlUrl);
            document.FooterTemplate.AddElement(footerHtmlToPdf);

            // add page number to the footer
            TextElement pageNumberText = new TextElement(document.FooterTemplate.ClientRectangle.Width - 100, 30,
                                "This is page &p; of &P; pages", footerPageNumberFont);
            document.FooterTemplate.AddElement(pageNumberText);
        }
Beispiel #58
0
        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();
            }
        }
Beispiel #59
0
        /// <summary>
        /// Generates the PDF page.
        /// </summary>
        /// <param name="docPDF">The doc PDF.</param>
        /// <param name="xPathNavigator">The x path navigator.</param>
        internal void GeneratePDFPage(Document docPDF, XPathNavigator xpatpageNode,String strContext, bool isPageTitleApplicable)
        {
            objpdfHelper = new PDFHelper();
              try
              {
            strarrPageDetails = new string[5];
            strbHtml = new StringBuilder();
            strPageTitleHtml = new StringBuilder();
            strType1Html = string.Empty;
            objSPfile = null;
            objStream = new MemoryStream();
            XmlNamespaceManager objXMLnameSpaces = new XmlNamespaceManager(xpatpageNode.NameTable);
            objXMLnameSpaces.AddNamespace("PDF", "http://www.shell.com/");
            StrConnectType = xpatpageNode.GetAttribute("ConnectionType", objXMLnameSpaces.DefaultNamespace);

            ///Add First Page
            pdfBLL = new PdfBLL();

            strarrPageDetails[0] = xpatpageNode.GetAttribute("ActualColumnname", objXMLnameSpaces.DefaultNamespace);
            strarrPageDetails[1] = Constant.EQUALS;
            strarrPageDetails[2] = xpatpageNode.GetAttribute("AssetValue", objXMLnameSpaces.DefaultNamespace);
            strarrPageDetails[3] = xpatpageNode.GetAttribute("ReportName", objXMLnameSpaces.DefaultNamespace);
            strarrPageDetails[4] = xpatpageNode.GetAttribute("AssetType", objXMLnameSpaces.DefaultNamespace);
            IntPageId = Convert.ToInt32(xpatpageNode.GetAttribute("PageID", objXMLnameSpaces.DefaultNamespace));
            if (isPageTitleApplicable)
            {
            StrNarrative = pdfBLL.GetNarrative(IntPageId, strContext, Constant.LISTNARRATIVE);
            if (string.IsNullOrEmpty(StrNarrative))
                StrNarrative = "N/A";
            StrSignOffStatus = xpatpageNode.GetAttribute("SignOffStatus", objXMLnameSpaces.DefaultNamespace);
            switch (StrSignOffStatus)
            {
                case "Yes":
                    StrSignOffStatus = "Signed Off";
                    break;
                case "No":
                    StrSignOffStatus = "Not Signed Off";
                    break;
            }
            StrPageOwner = xpatpageNode.GetAttribute("PageOwner", objXMLnameSpaces.DefaultNamespace);
            StrPageTitle = xpatpageNode.GetAttribute("Title", objXMLnameSpaces.DefaultNamespace);
            xpatpageNode.MoveToParent();
            StrAssetValue = xpatpageNode.GetAttribute("AssetValue", objXMLnameSpaces.DefaultNamespace);
            StrPageTitle = StrPageTitle.Replace("$", StrAssetValue);
            #region PageTitleHtml
            strPageTitleHtml.Append(@"<table width=""90%"" align=""center"" style="" font-family:Verdana;font-size:42px;font-weight:bold;"" >
                                      <tr >
                                        <td align=""center"" width=""40%"" style=""padding-right: 8px; height: 600px;"">
                                          <b>");
            strPageTitleHtml.Append(StrPageTitle);
            strPageTitleHtml.Append(@" </b></td>
                                      </tr>
                                      </table>
                                    <table width=""70%"" align=""center"" style="" font-family:Verdana;font-size:20px;
                                        background-color:Black;border:solid 1px Black;"" cellpadding=""2"" cellspacing=""2"" >
                                      <tr style=""background-color:White;"">
                                        <td align=""right"" width=""40%"" style=""padding-right: 8px; height: 21px;"">
                                          <b>Page Owner</b></td>
                                        <td align=""left"" width=""60%"" style=""height: 21px"">
                                          ");
            strPageTitleHtml.Append(StrPageOwner);
            strPageTitleHtml.Append(@" </td>
                                      </tr>
                                      <tr style=""background-color:White;"">
                                        <td align=""right"" style=""padding-right: 8px;"">
                                          <b>Sign Off Status</b></td>
                                        <td align=""left"" >
                                          ");
            strPageTitleHtml.Append(StrSignOffStatus);
            strPageTitleHtml.Append(@"</td>
                                      </tr>
                                      <tr style=""height:100px;background-color:White;"">
                                        <td align=""right"" style=""padding-right: 8px;"" valign=""top"">
                                          <b>Narrative</b></td>
                                        <td align=""left"" valign=""top"">
                                          ");
            strPageTitleHtml.Append(StrNarrative);
            strPageTitleHtml.Append(@"</td>
                                      </tr>
                                  </table>");
            #endregion
            objpdfHelper.AddHTMLtoPDF(docPDF, Convert.ToString(strPageTitleHtml), strContext, false);
            }
            switch (StrConnectType)
            {
              case "1":
              try
              {
                  strType1Html = objpdfHelper.AddType1toPDFDoc(strarrPageDetails, strContext);
                  strbHtml.Append(Constant.HEAD);
                  strbHtml.Append(strType1Html);
                  strbHtml.Append(Constant.END);
                  HtmlToPdfElement htmlToPdfElement;
                  htmlToPdfElement = new HtmlToPdfElement(0, 0, -1, -1, Convert.ToString(strbHtml), HttpContext.Current.Request.Url.ToString());
                  htmlToPdfElement.FitWidth = true;
                  htmlToPdfElement.EmbedFonts = true;
                  htmlToPdfElement.LiveUrlsEnabled = true;
                  htmlToPdfElement.ScriptsEnabled = true;
                  htmlToPdfElement.ActiveXEnabled = true;
                  htmlToPdfElement.PdfBookmarkOptions.TagNames = null;
                  //Add a first page to the document. The next pages will inherit the settings from this page
                  PdfPage page = docPDF.Pages.AddNewPage(PageSize.A4, new Margins(10, 10, 0, 0), PageOrientation.Portrait);
                  page.AddElement(htmlToPdfElement);
              }
              catch (SoapException soapEx)
              {
                  objpdfHelper.AddWarningTitleToNewPDfPage(docPDF,soapEx.Message);
              }
              catch (WebException ex)
              {
                  objpdfHelper.AddWarningTitleToNewPDfPage(docPDF, ex.Message);
              }

            break;
              case "2":
            objSPfile = pdfBLL.DownloadFileFromDocumentLibrary(strContext, Constant.LISTPUBLISHEDDOCUMENTS,
                                                          Convert.ToString(IntPageId));
            objpdfHelper.AddFiletoPDFDoc(docPDF, objSPfile);
            break;
              case "3":
            objSPfile = pdfBLL.DownloadFileFromDocumentLibrary(strContext, Constant.LISTUSERDEFINEDDOCUMENTS,
                                                          Convert.ToString(IntPageId));
            objpdfHelper.AddFiletoPDFDoc(docPDF, objSPfile);
            break;
            }
              }
              catch (Exception ex)
              {
              objpdfHelper.PrintLog(strContext, ex.Message, "BookPage.GeneratePDFPage", "Exception");
              objpdfHelper.PrintLog(strContext, ex.StackTrace, "BookPage.GeneratePDFPage", "Exception");
            throw;
              }
              finally {
            objStream.Dispose();
              }
        }