public ActionResult ConvertHtmlToPdf(IFormCollection collection)
        {
            // Create a PDF document
            Document pdfDocument = new Document();

            // Set license key received after purchase to use the converter in licensed mode
            // Leave it not set to use the converter in demo mode
            pdfDocument.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";

            // Create a PDF page where to add the first HTML
            PdfPage firstPdfPage = pdfDocument.AddPage();

            try
            {
                // The image location in PDF
                float xLocation = float.Parse(collection["xLocationTextBox"]);
                float yLocation = float.Parse(collection["yLocationTextBox"]);

                // The URL of the HTML page to convert to an image in PDF
                string urlToConvert = collection["urlTextBox"];

                // Create the HTML to Image element
                HtmlToImageElement htmlToImageElement = new HtmlToImageElement(xLocation, yLocation, urlToConvert);

                // Optionally set the HTML viewer width
                htmlToImageElement.HtmlViewerWidth = int.Parse(collection["htmlViewerWidthTextBox"]);

                // Optionally set the HTML viewer height
                if (collection["htmlViewerHeightTextBox"][0].Length > 0)
                {
                    htmlToImageElement.HtmlViewerHeight = int.Parse(collection["htmlViewerHeightTextBox"]);
                }

                // Optionally set the HTML content clipping option to force the HTML content width to be exactly HtmlViewerWidth pixels
                htmlToImageElement.ClipHtmlView = collection["clipContentCheckBox"].Count > 0;

                // Optionally set the destination width in PDF
                if (collection["contentWidthTextBox"][0].Length > 0)
                {
                    htmlToImageElement.Width = float.Parse(collection["contentWidthTextBox"]);
                }

                // Optionally set the destination height in PDF
                if (collection["contentHeightTextBox"][0].Length > 0)
                {
                    htmlToImageElement.Height = float.Parse(collection["contentHeightTextBox"]);
                }

                // Optionally set a delay before conversion to allow asynchonous scripts to finish
                htmlToImageElement.ConversionDelay = 2;

                // Add the HTML to Image element to PDF document
                // The AddElementResult contains the bounds of the HTML to Image Element in last rendered PDF page
                // such that you can start a new PDF element right under it
                AddElementResult result = firstPdfPage.AddElement(htmlToImageElement);

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

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

                return(fileResult);
            }
            finally
            {
                // Close the PDF document
                pdfDocument.Close();
            }
        }
        protected void 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();
            }
        }
示例#3
0
        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;
                }
            }
        }
        ////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;
            //    }
            //}
        }
示例#5
0
        ////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;
            //    }
            //}
        }
示例#6
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=";

            // Create a PDF page where to add the first HTML
            PdfPage firstPdfPage = pdfDocument.AddPage();

            // The image location in PDF
            float xLocation = float.Parse(xLocationTextBox.Text);
            float yLocation = float.Parse(yLocationTextBox.Text);

            // The URL of the HTML page to convert to an image in PDF
            string urlToConvert = urlTextBox.Text;

            // Create the HTML to Image element
            HtmlToImageElement htmlToImageElement = new HtmlToImageElement(xLocation, yLocation, urlToConvert);

            // Optionally set the HTML viewer width
            htmlToImageElement.HtmlViewerWidth = int.Parse(htmlViewerWidthTextBox.Text);

            // Optionally set the HTML viewer height
            if (htmlViewerHeightTextBox.Text.Length > 0)
            {
                htmlToImageElement.HtmlViewerHeight = int.Parse(htmlViewerHeightTextBox.Text);
            }

            // Optionally set the HTML content clipping option to force the HTML content width to be exactly HtmlViewerWidth pixels
            htmlToImageElement.ClipHtmlView = clipContentCheckBox.Checked;

            // Optionally set the destination width in PDF
            if (contentWidthTextBox.Text.Length > 0)
            {
                htmlToImageElement.Width = float.Parse(contentWidthTextBox.Text);
            }

            // Optionally set the destination height in PDF
            if (contentHeightTextBox.Text.Length > 0)
            {
                htmlToImageElement.Height = float.Parse(contentHeightTextBox.Text);
            }

            // Optionally set a delay before conversion to allow asynchonous scripts to finish
            htmlToImageElement.ConversionDelay = 2;

            // Add the HTML to Image element to PDF document
            // The AddElementResult contains the bounds of the HTML to Image Element in last rendered PDF page
            // such that you can start a new PDF element right under it
            firstPdfPage.AddElement(htmlToImageElement);

            // 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=Add_HTML_to_Image_Elements_to_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();
        }