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();
            }
        }
예제 #2
0
        protected void btnConvert_Click(object sender, EventArgs e)
        {
            MemoryStream pdfStream2 = null;

            try
            {
                PdfConverter pdfConverter = new PdfConverter();

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

                // Convert the first document and produce a Document object containing the conversion result
                Document document1 = pdfConverter.GetPdfDocumentObjectFromUrl(textBoxWebPageURL1.Text);

                // Load a second document from a stream produced by the conversion of the second URL
                byte[] doc2Bytes = pdfConverter.GetPdfBytesFromUrl(textBoxWebPageURL2.Text);
                pdfStream2 = new MemoryStream(doc2Bytes);

                // Load a PDF document from a stream
                Document document2 = new Document(pdfStream2);

                // Append second to the first document
                document1.AppendDocument(document2);

                // Convert the third URL to PDF and obtain a PDF document object
                Document document3 = pdfConverter.GetPdfDocumentObjectFromUrl(textBoxWebPageURL3.Text);

                // Append the third document after the second
                document1.AppendDocument(document3);

                // When AutoCloseAppendedDocs property is set on true the appended documents are automatically closed
                // when the document to which they are appended is closed
                document1.AutoCloseAppendedDocs = true;

                byte[] pdfBytes = null;

                try
                {
                    pdfBytes = document1.Save();
                }
                finally
                {
                    // Close the Document to realease all the resources
                    // The appended document3 will be automatically closed also
                    document1.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=HtmlToPdfFeatures.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
            {
                if (pdfStream2 != null)
                    pdfStream2.Close();
            }
        }
        protected void btnConvert_Click(object sender, EventArgs e)
        {
            PdfConverter pdfConverter = new PdfConverter();

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

            // inform the converter about the HTML elements for which we want the location in PDF
            // in this sample we want the location of IMG, H1 and H2 elements and the elements with ID
            // equal to 'id1' or 'id2'
            pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors = new string[] { "IMG", "H1", "H2", "#id1", "#id2" };

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

            // iterate over the HTML elements locations and hightlight each element with a green rectangle
            foreach (HtmlElementMapping elementMapping in pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult)
            {
                // because a HTML element can span over many PDF pages the mapping
                // of the HTML element in PDF document consists in a list of rectangles,
                // one rectangle for each PDF page where this element was rendered
                foreach (HtmlElementPdfRectangle elementLocationInPdf in elementMapping.PdfRectangles)
                {
                    // get the PDF page
                    PdfPage pdfPage = pdfDocument.Pages[elementLocationInPdf.PageIndex];
                    RectangleF pdfRectangleInPage = elementLocationInPdf.Rectangle;

                    // create a RectangleElement to highlight the HTML element
                    RectangleElement highlightRectangle = new RectangleElement(pdfRectangleInPage.X, pdfRectangleInPage.Y,
                        pdfRectangleInPage.Width, pdfRectangleInPage.Height);
                    highlightRectangle.ForeColor = Color.Green;

                    pdfPage.AddElement(highlightRectangle);
                }
            }

            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=HtmlElementsLocation.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();
        }
예제 #4
0
        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();
        }
예제 #5
0
        public void CreatePDf(string pageUrl, string saveDestination)
        {
            #region Create PDF
            try
            {
                PdfConverter pdfConverter = new PdfConverter();
                pdfConverter.InternetSecurityZone = InternetSecurityZone.Trusted;

                //pdfConverter.AuthenticationOptions
                pdfConverter.AuthenticationOptions.Username          = HttpContext.Current.User.Identity.Name;
                pdfConverter.HtmlElementsMappingOptions.HtmlTagNames = new string[] { "form" };
                pdfConverter.PdfDocumentOptions.PdfPageSize          = ExpertPdf.HtmlToPdf.PdfPageSize.A4;
                pdfConverter.PdfDocumentOptions.PdfCompressionLevel  = PdfCompressionLevel.Normal;
                pdfConverter.PdfDocumentOptions.ShowHeader           = true;
                pdfConverter.PdfDocumentOptions.ShowFooter           = true;
                pdfConverter.PdfDocumentOptions.LeftMargin           = 10;
                pdfConverter.PdfDocumentOptions.RightMargin          = 10;
                pdfConverter.PdfDocumentOptions.TopMargin            = 10;
                pdfConverter.PdfDocumentOptions.BottomMargin         = 10;


                #region Header Part Commented
                // pdfConverter.PdfDocumentOptions.ShowHeader = true;
                //  pdfConverter.PdfHeaderOptions.HeaderText = "sample header: " + "header data";
                // pdfConverter.PdfHeaderOptions.HeaderTextColor = System.Drawing.Color.Blue;
                // pdfConverter.PdfHeaderOptions.header = string.empty;
                //  pdfConverter.PdfHeaderOptions.DrawHeaderLine = false;

                // pdfConverter.PdfFooterOptions.FooterText = "Sample footer: " + "foooter Content" +
                // ". You can change color, font and other options";
                // pdfConverter.PdfFooterOptions.FooterTextColor = System.Drawing.Color.Blue;
                // pdfConverter.PdfFooterOptions.DrawFooterLine = false;
                // pdfConverter.PdfFooterOptions.PageNumberText = "Page";
                // pdfConverter.PdfFooterOptions.ShowPageNumber = true;
                //System.Web.HttpResponse response = System.Web.HttpContext.Current.Response;
                //response.Clear();
                //response.AddHeader("Content-Type", "binary/octet-stream");
                //response.AddHeader("Content-Disposition",
                //  "attachment; filename=" + "ExpertPdf-Trail-" + DateTime.Now.ToShortDateString() + "; size=" + downloadBytes.Length.ToString());
                //response.Flush();
                //response.BinaryWrite(downloadBytes);
                //response.Flush();
                //response.End();

                #endregion

                ExpertPdf.HtmlToPdf.PdfDocument.Document pdfDocument = pdfConverter.GetPdfDocumentObjectFromUrl(pageUrl);
                PdfFont stdTimesFont = pdfDocument.AddFont(StdFontBaseFamily.TimesRoman);
                stdTimesFont.Size = 50;
                //  byte[] downloadBytes = pdfConverter.GetPdfFromUrlBytes(pageUrl);

                foreach (HtmlElementMapping elementMapping in pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult)
                {
                    foreach (HtmlElementPdfRectangle elementLocationInPdf in elementMapping.PdfRectangles)
                    {
                        // get the PDF page
                        ExpertPdf.HtmlToPdf.PdfDocument.PdfPage pdfPage = pdfDocument.Pages[elementLocationInPdf.PageIndex];

                        {
                            float xPos        = -5;
                            float yPos        = 370;
                            float rotateAngle = -45;
                            for (int i = 0; i < 2; i++)
                            {
                                TextElement watermarkTextElement = new TextElement(xPos, yPos, PDFReportConstants.WaterMarkText, stdTimesFont);
                                watermarkTextElement.ForeColor    = System.Drawing.Color.LightGray;
                                watermarkTextElement.Transparency = 85;
                                watermarkTextElement.Rotate(rotateAngle);

                                // watermarkTemplate.AddElement(watermarkTextElement);
                                pdfPage.AddElement(watermarkTextElement);
                                xPos        = 0;
                                rotateAngle = rotateAngle + 5;
                                // xPos = xPos + 100;
                                yPos = yPos + 200;
                            }
                        }
                    }
                }

                string outFile = saveDestination;

                //string filepath =HttpContext.Current.Server.MapPath("~/Templates/Risk Rating Template/Risk_Rating_Template.xlsx");

                pdfDocument.Save(saveDestination);
                #region Commented Part
                // the code below can be replaced by pdfMerger.SaveMergedPDFToFile(outFile);
                //System.IO.FileStream fs = null;
                //fs = new System.IO.FileStream(outFile, System.IO.FileMode.Create, System.IO.FileAccess.ReadWrite, System.IO.FileShare.Read);
                //fs.Write(downloadBytes, 0, downloadBytes.Length);
                //fs.Close();
                #endregion

                System.Diagnostics.Process.Start(outFile);
            }

            catch (Exception ex)
            {
                //LogManager.GetLogger(LogCategory.Error).Log(ex, LoginextLogUtility.EXP_LOG_AND_RETHROW);
            }
            #endregion
        }
        protected void btnConvert_Click(object sender, EventArgs e)
        {
            PdfConverter pdfConverter = new PdfConverter();

            // show the bookmarks when the document is opened
            pdfConverter.PdfViewerPreferences.PageMode = ViewerPageMode.UseOutlines;

            // set top and bottom page margins
            pdfConverter.PdfDocumentOptions.TopMargin = 5;
            pdfConverter.PdfDocumentOptions.BottomMargin = 5;

            // Inform the converter about the HTML elements for which we want the location in PDF
            // In this sample we want the location of the entries in the Table of Contents
            // The HTML ID of each entry in the table of contents is of form TOCEntry_{EntryIndex}_ID
            // the HTML ID of each target of a table of contents entry is of form TOCEntry_{EntryIndex}_Target_ID

            // Both toc entries and toc entries targets locations in PDF will be retrieved
            // and therefore the number of IDs is twice TOC entries number
            pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors = new string[2 * TOC_ENTRIES_COUNT];

            int mappingsTableIdx = 0;
            for (int tocEntryIndex = 1; tocEntryIndex <= TOC_ENTRIES_COUNT; tocEntryIndex++)
            {
                // add the HTML ID of the TOC entry element to the list of elements for which we want the PDF location
                string tocEntryID = String.Format("#TOCEntry_{0}_ID", tocEntryIndex);
                pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors[mappingsTableIdx++] = tocEntryID;

                // add the HTML ID of the TOC entry target element to the list of elements for which we want the PDF location
                string tocEntryTargetID = String.Format("#TOCEntry_{0}_Target_ID", tocEntryIndex);
                pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors[mappingsTableIdx++] = tocEntryTargetID;
            }

            // set bookmark options
            pdfConverter.PdfBookmarkOptions.HtmlElementSelectors = new string[] { "A[class=\"bookmark\"]" };

            // the URL of the HTML document to convert
            string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri;
            string htmlBookFilePath = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HtmlBook/Book.htm";

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

            // Create a font used to write the page numbers in the table of contents
            PdfFont pageNumberFont = pdfDocument.Fonts.Add(new Font("Arial", PAGE_NUMBER_FONT_SIZE, FontStyle.Bold, GraphicsUnit.Point), true);

            // get the right edge of the table of contents where to position the page numbers
            float tocEntryMaxRight = 0.0f;
            for (int tocEntryIdx = 1; tocEntryIdx <= TOC_ENTRIES_COUNT; tocEntryIdx++)
            {
                string tocEntryID = String.Format("TOCEntry_{0}_ID", tocEntryIdx);
                HtmlElementMapping tocEntryLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryID);
                if (tocEntryLocation.PdfRectangles[0].Rectangle.Right > tocEntryMaxRight)
                    tocEntryMaxRight = tocEntryLocation.PdfRectangles[0].Rectangle.Right;
            }

            // Add page number for each entry in the table of contents
            for (int tocEntryIdx = 1; tocEntryIdx <= TOC_ENTRIES_COUNT; tocEntryIdx++)
            {
                string tocEntryID = String.Format("TOCEntry_{0}_ID", tocEntryIdx);
                string tocEntryTargetID = String.Format("TOCEntry_{0}_Target_ID", tocEntryIdx);

                HtmlElementMapping tocEntryLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryID);
                HtmlElementMapping tocEntryTargetLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryTargetID);

                // get the TOC entry page and bounds
                PdfPage tocEntryPdfPage = pdfDocument.Pages[tocEntryLocation.PdfRectangles[0].PageIndex];
                RectangleF tocEntryPdfRectangle = tocEntryLocation.PdfRectangles[0].Rectangle;

                // get the page number of target where the TOC entry points
                int tocEntryTargetPageNumber = tocEntryTargetLocation.PdfRectangles[0].PageIndex + 1;

                // add dashed line from text entry to the page number
                LineElement lineToNumber = new LineElement(tocEntryPdfRectangle.Right + 5, tocEntryPdfRectangle.Y + tocEntryPdfRectangle.Height / 2,
                        tocEntryMaxRight + 80, tocEntryPdfRectangle.Y + tocEntryPdfRectangle.Height / 2);
                lineToNumber.LineStyle.LineWidth = 1;
                lineToNumber.LineStyle.LineDashStyle = LineDashStyle.Dash;
                lineToNumber.ForeColor = Color.Green;
                tocEntryPdfPage.AddElement(lineToNumber);

                // create the page number text element to the right of the TOC entry
                TextElement pageNumberTextEement = new TextElement(tocEntryMaxRight + 85, tocEntryPdfRectangle.Y, -1, tocEntryPdfRectangle.Height,
                        tocEntryTargetPageNumber.ToString(), pageNumberFont);
                pageNumberTextEement.TextAlign = HorizontalTextAlign.Left;
                pageNumberTextEement.VerticalTextAlign = VerticalTextAlign.Middle;
                pageNumberTextEement.ForeColor = Color.Blue;

                // add the page number to the right of the TOC entry
                tocEntryPdfPage.AddElement(pageNumberTextEement);
            }

            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=TableOfContents.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();
        }
예제 #7
0
        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;
            }
        }
예제 #8
0
        private void btnConvertMerge_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            MemoryStream pdfStream2 = null;

            try
            {
                PdfConverter pdfConverter = new PdfConverter();

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

                // Convert the first document and produce a Document object containing the conversion result
                Document document1 = pdfConverter.GetPdfDocumentObjectFromUrl(textBoxURL1.Text);

                // Load a second document from a stream produced by the conversion of the second URL
                byte[] doc2Bytes = pdfConverter.GetPdfBytesFromUrl(textBoxURL2.Text);
                pdfStream2 = new MemoryStream(doc2Bytes);

                // Load a PDF document from a stream
                Document document2 = new Document(pdfStream2);

                // Append second to the first document
                document1.AppendDocument(document2);

                // Convert the third URL to PDF and obtain a PDF document object
                Document document3 = pdfConverter.GetPdfDocumentObjectFromUrl(textBoxURL3.Text);

                // Append the third document after the second
                document1.AppendDocument(document3);

                // When AutoCloseAppendedDocs property is set on true the appended documents are automatically closed
                // when the document to which they are appended is closed
                document1.AutoCloseAppendedDocs = true;

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

                try
                {
                    document1.Save(outFilePath);
                }
                finally
                {
                    // Close the Document to realease all the resources
                    // The appended document2 and document3 will be automatically closed
                    document1.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
            {
                // close the memory stream
                if (pdfStream2 != null)
                    pdfStream2.Close();

                this.Cursor = Cursors.Arrow;
            }
        }
예제 #9
0
        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;
            }
        }
예제 #10
0
         /// <summary>
         /// Function Creates PDF from HTML WITH TOC and Header-Footer
         /// </summary>
         /// <param name="PDFPath"></param>
        private void CreatePDF(string PDFPath)
        {
            #region Private Variables
            PdfConverter pdfConverter = new PdfConverter();
            int mappingsTableIdx = 0;
            Document document = new Document(); //New document to be used for adding blank pages
            Document mergedDocument = new Document(); //New Document to merge Header and Pdfdocument
            string coverImg = string.Empty;
            float tocEntryMaxRight = 0.0f;
            int cntAddIndxForPage = 0;
            List<string> lstHeader = new List<string>();
            int pageNum = 0;
            string strHeader = string.Empty;
            List<int> lstBlankPage = new List<int>();
            #endregion           
            // show the bookmarks when the document is opened
            pdfConverter.PdfViewerPreferences.PageMode = ViewerPageMode.UseNone;
            // set page margins
            pdfConverter.PdfDocumentOptions.TopMargin = 20;
            pdfConverter.PdfDocumentOptions.BottomMargin = 20;
            pdfConverter.PdfDocumentOptions.LeftMargin = 20;
            pdfConverter.PdfDocumentOptions.RightMargin = 20;
            pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.Letter11x17;
            pdfConverter.PdfDocumentOptions.FitWidth = false;
            pdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait;
            pdfConverter.AvoidImageBreak = true;
            pdfConverter.AvoidTextBreak = true;
            // Inform the converter about the HTML elements for which we want the location in PDF
            // The HTML ID of each entry in the table of contents is of form TOCEntry_{EntryIndex}_ID
            // the HTML ID of each target of a table of contents entry is of form TOCEntry_{EntryIndex}_Target_ID
            // Both toc entries and toc entries targets locations in PDF will be retrieved
            // and therefore the number of IDs is twice TOC entries number
            pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors = new string[2 * countTOC];
                       
            for (int tocEntryIndex = 1; tocEntryIndex <= countTOC; tocEntryIndex++)
            {
                // add the HTML ID of the TOC entry element to the list of elements for which we want the PDF location
                string tocEntryID = String.Format(PDFConstants.Instance.TOCENTRYID, tocEntryIndex);
                pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors[mappingsTableIdx++] = tocEntryID;
                // add the HTML ID of the TOC entry target element to the list of elements for which we want the PDF location
                string tocEntryTargetID = String.Format(PDFConstants.Instance.TOCTARGETID , tocEntryIndex);
                pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors[mappingsTableIdx++] = tocEntryTargetID;
            }
            // set bookmark options
            pdfConverter.PdfBookmarkOptions.HtmlElementSelectors = new string[] { PDFConstants.Instance.HTMLBookmarkTag };

            // the URL of the HTML document to convert
            string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri;
            string htmlBookFilePath = Path.Combine(HttpContext.Current.Server.MapPath("~/data"), "temp.html");

            // show header in rendered PDF
            pdfConverter.PdfDocumentOptions.ShowHeader = true;
            
            //Add pages to header Document
            coverImg = Path.Combine(HttpContext.Current.Server.MapPath("~/Images"), "Cover.jpg");
            Document header = pdfConverter.GetPdfDocumentObjectFromHtmlString(string.Format(PDFConstants.Instance.HTMLCoverImageTag,coverImg ) +
                                 PDFConstants.Instance. HTMLMETAContentTag);

            // call the converter and get a Document object from URL
            Document pdfDocument = pdfConverter.GetPdfDocumentObjectFromUrl(htmlBookFilePath);
            pdfDocument.ViewerPreferences.CenterWindow = true;

            // Create a font used to write the page numbers in the table of contents
            PdfFont pageNumberFont = pdfDocument.Fonts.Add(new Font("Times New Roman", PAGE_NUMBER_FONT_SIZE, FontStyle.Regular, GraphicsUnit.Point), true);

            #region Generate TOC & Add to PDF

            // get the right edge of the table of contents where to position the page numbers            
            for (int tocEntryIdx = 1; tocEntryIdx <= countTOC; tocEntryIdx++)
            {
                string tocEntryID = String.Format("TOCEntry_{0}_ID", tocEntryIdx);
                HtmlElementMapping tocEntryLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryID);
                if (tocEntryLocation != null)
                {
                    if (tocEntryLocation.PdfRectangles[0].Rectangle.Right > tocEntryMaxRight)
                        tocEntryMaxRight = tocEntryLocation.PdfRectangles[0].Rectangle.Right;
                }
            }            

            // Add page number for each entry in the table of contents
            for (int tocEntryIdx = 1; tocEntryIdx <= countTOC; tocEntryIdx++)
            {
                string tocEntryID = String.Format("TOCEntry_{0}_ID", tocEntryIdx);
                string tocEntryTargetID = String.Format("TOCEntry_{0}_Target_ID", tocEntryIdx);

                HtmlElementMapping tocEntryLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryID);
                HtmlElementMapping tocEntryTargetLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryTargetID);

               // get the TOC entry page and bounds
                PdfPage tocEntryPdfPage = pdfDocument.Pages[tocEntryLocation.PdfRectangles[0].PageIndex];
                RectangleF tocEntryPdfRectangle = tocEntryLocation.PdfRectangles[0].Rectangle;

                if (tocEntryLocation.HtmlElementCssClassName.Equals("h1"))
                {
                    while (pageNum < tocEntryTargetLocation.PdfRectangles[0].PageIndex + 1 + cntAddIndxForPage)
                    {
                        pageNum++;
                        lstHeader.Add(strHeader);
                    }

                    if ((tocEntryTargetLocation.PdfRectangles[0].PageIndex + 1 + cntAddIndxForPage) % 2 == 0)
                    {
                        pdfDocument.Pages.Insert(tocEntryTargetLocation.PdfRectangles[0].PageIndex + cntAddIndxForPage, document.AddPage(PageSize.Letter11x17, Margins.Empty));
                        lstBlankPage.Add(tocEntryTargetLocation.PdfRectangles[0].PageIndex + cntAddIndxForPage + 1);
                        cntAddIndxForPage++;
                    }
                    strHeader = tocEntryLocation.HtmlElementText;
                }
               // get the page number of target where the TOC entry points
                int tocEntryTargetPageNumber = tocEntryTargetLocation.PdfRectangles[0].PageIndex + 1 + cntAddIndxForPage;

                // add dashed line from text entry to the page number
                LineElement lineToNumber = new LineElement(tocEntryPdfRectangle.Right + 5, tocEntryPdfRectangle.Y + tocEntryPdfRectangle.Height / 1.2F,
                        tocEntryMaxRight + 200, tocEntryPdfRectangle.Y + tocEntryPdfRectangle.Height / 1.2F);
                lineToNumber.LineStyle.LineWidth = 1;
                lineToNumber.LineStyle.LineDashStyle = LineDashStyle.Dot;
                lineToNumber.ForeColor = Color.Black;                
                tocEntryPdfPage.AddElement(lineToNumber);
                
                // create the page number text element to the right of the TOC entry
                TextElement pageNumberTextEement = new TextElement(tocEntryMaxRight + 205, tocEntryPdfRectangle.Y, -1, tocEntryPdfRectangle.Height,
                tocEntryTargetPageNumber.ToString(), pageNumberFont);
                pageNumberTextEement.TextAlign = HorizontalTextAlign.Left;
                pageNumberTextEement.VerticalTextAlign = VerticalTextAlign.Middle;
                pageNumberTextEement.ForeColor = Color.Black;
                // add the page number to the right of the TOC entry
                tocEntryPdfPage.AddElement(pageNumberTextEement);
            }

            #endregion

            #region Create index at End of the Document

            int TOC_INDEX_COUNT = NewIndexList.Count;
            pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors = new string[2 * TOC_INDEX_COUNT];

            int mappingsEntryTableIdx = 0;
            for (int tocEntryIndex = 1; tocEntryIndex <= TOC_INDEX_COUNT; tocEntryIndex++)
            {
                // add the HTML ID of the TOC entry element to the list of elements for which we want the PDF location
                string tocEntryID = String.Format("#TOCIndex_{0}_ID", NewIndexList[tocEntryIndex - 1].ToString());
                pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors[mappingsEntryTableIdx++] = tocEntryID;

                string tocEntryTargetID = String.Format("#TOCIndex_{0}_Target_ID", NewIndexList[tocEntryIndex - 1].ToString());
                pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors[mappingsEntryTableIdx++] = tocEntryTargetID;
            }

            // call the converter and get a Document object from URL
            Document pdfDocumentI = pdfConverter.GetPdfDocumentObjectFromUrl(htmlBookFilePath);

            // Create a font used to write the page numbers in the table of contents
            PdfFont pageNumberFontI = pdfDocument.Fonts.Add(new Font("Arial", PAGE_NUMBER_FONT_SIZE, FontStyle.Bold, GraphicsUnit.Point), true);

            // get the right edge of the Index where to position the page numbers
            float tocEntryMaxRightI = 0.0f;
            for (int tocEntryIdx = 1; tocEntryIdx <= TOC_INDEX_COUNT; tocEntryIdx++)
            {
                string tocEntryID = String.Format("TOCIndex_{0}_ID", tocEntryIdx);
                HtmlElementMapping tocEntryLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryID);
                if (tocEntryLocation != null)
                {
                    if (tocEntryLocation.PdfRectangles[0].Rectangle.Right > tocEntryMaxRightI)
                        tocEntryMaxRightI = tocEntryLocation.PdfRectangles[0].Rectangle.Right;
                }
            }
            // Add page number for each entry in the Index
            for (int tocEntryIdx = 1; tocEntryIdx <= TOC_INDEX_COUNT; tocEntryIdx++)
            {
                string tocEntryID = String.Format("TOCIndex_{0}_ID", NewIndexList[tocEntryIdx - 1].ToString());
                string tocEntryTargetID = String.Format("TOCIndex_{0}_Target_ID", NewIndexList[tocEntryIdx - 1].ToString());

                HtmlElementMapping tocEntryLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryID);
                HtmlElementMapping tocEntryTargetLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryTargetID);

                // get the TOC entry page and bounds
                PdfPage tocEntryPdfPage = pdfDocument.Pages[tocEntryLocation.PdfRectangles[0].PageIndex + cntAddIndxForPage];
                RectangleF tocEntryPdfRectangle = tocEntryLocation.PdfRectangles[0].Rectangle;

                // get the page number of target where the TOC entry points
                int tocEntryTargetPageNumber = tocEntryTargetLocation.PdfRectangles[0].PageIndex + 1;

                for (int i = 0; i < lstBlankPage.Count; i++)
                {
                    if (lstBlankPage[i] <= tocEntryTargetPageNumber)
                    {
                        tocEntryTargetPageNumber++;
                    }
                }

                // add dashed line from text entry to the page number
                LineElement lineToNumber = new LineElement(tocEntryPdfRectangle.Right + 5, tocEntryPdfRectangle.Y + tocEntryPdfRectangle.Height / 1.2F,
                        tocEntryMaxRight, tocEntryPdfRectangle.Y + tocEntryPdfRectangle.Height / 1.2F);
                lineToNumber.LineStyle.LineWidth = 1;
                lineToNumber.LineStyle.LineDashStyle = LineDashStyle.Dot;
                lineToNumber.ForeColor = Color.Black;
                tocEntryPdfPage.AddElement(lineToNumber);

                // create the page number text element to the right of the TOC entry
                TextElement pageNumberTextEement = new TextElement(tocEntryMaxRight + 5, tocEntryPdfRectangle.Y, -1, tocEntryPdfRectangle.Height,
                tocEntryTargetPageNumber.ToString(), pageNumberFont);
                pageNumberTextEement.TextAlign = HorizontalTextAlign.Left;
                pageNumberTextEement.VerticalTextAlign = VerticalTextAlign.Middle;
                pageNumberTextEement.ForeColor = Color.Black;

                // add the page number to the right of the TOC entry
                tocEntryPdfPage.AddElement(pageNumberTextEement);
            }
            #endregion

            #region Set Header On Each Pages

            // the width is given by the PDF page width
            float altHeaderFooterWidth = pdfDocument.Pages[0].ClientRectangle.Width;
            float altHeaderHeight = pdfConverter.PdfHeaderOptions.HeaderHeight;

            //Add Header Chapter for last chapter in Header list
            for (int pages = lstHeader.Count; pages < pdfDocument.Pages.Count; pages++)
            {
                lstHeader.Add(strHeader);
            }

            //Remove Unnecessary Header Line from Header Document
            for (int pageIndex = 0; pageIndex < header.Pages.Count; pageIndex++)
            {
                Template tmpHeaderTemplate = pdfDocument.Templates.AddNewTemplate(altHeaderFooterWidth, altHeaderHeight);
                PdfPage pdfPage = header.Pages[pageIndex];
                pdfPage.CustomHeaderTemplate = tmpHeaderTemplate;
                pdfPage.ShowHeaderTemplate = true;
            }

            //Iterate through pages and add header details on each page.. i.e. Chapter Name, Page Number
            for (int pageIndex = 0; pageIndex < pdfDocument.Pages.Count; pageIndex++)
            {
                // create the alternate header template
                Template altHeaderTemplate = pdfDocument.Templates.AddNewTemplate(altHeaderFooterWidth, altHeaderHeight);
                TextElement txtHeader = new TextElement(10, altHeaderHeight, lstHeader[pageIndex].ToString(), pageNumberFont, Color.Black);
                altHeaderTemplate.AddElement(txtHeader);

                TextElement txtPageNumber = new TextElement(altHeaderFooterWidth - 50, altHeaderHeight, (pageIndex + 1).ToString(), pageNumberFont, Color.Black);
                altHeaderTemplate.AddElement(txtPageNumber);

                PdfPage pdfPage = pdfDocument.Pages[pageIndex];
                pdfPage.CustomHeaderTemplate = altHeaderTemplate;
                pdfPage.ShowHeaderTemplate = true;
            }

            #endregion

            mergedDocument.AppendDocument(header);
            mergedDocument.AppendDocument(pdfDocument);

           try
            {
                mergedDocument.Save(PDFPath);
            }
            finally
            {
                // close the Documents to realease all the resources
                mergedDocument.Close();
                header.Close();
                pdfDocument.Close();
                document.Close();
                pdfDocumentI.Close();
                lstBlankPage.Clear();
                TOC_INDEX_COUNT = 0;
                FreeResources();
            }
        }
예제 #11
0
        private void btnConvert_Click(object sender, EventArgs e)
        {
            this.Cursor = Cursors.WaitCursor;

            try
            {
                PdfConverter pdfConverter = new PdfConverter();

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

                // inform the converter about the HTML elements for which we want the location in PDF
                // in this sample we want the location of IMG, H1 and H2 elements and the elements having ID 'id1' or 'id2'
                pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors = new string[] { "IMG", "H1", "H2", "#id1", "#id2" };

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

                // iterate over the HTML elements locations and hightlight each element with a green rectangle
                foreach (HtmlElementMapping elementMapping in pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult)
                {
                    // because a HTML element can span over many PDF pages the mapping
                    // of the HTML element in PDF document consists in a list of rectangles,
                    // one rectangle for each PDF page where this element was rendered
                    foreach (HtmlElementPdfRectangle elementLocationInPdf in elementMapping.PdfRectangles)
                    {
                        // get the PDF page
                        PdfPage pdfPage = pdfDocument.Pages[elementLocationInPdf.PageIndex];
                        RectangleF pdfRectangleInPage = elementLocationInPdf.Rectangle;

                        // create a RectangleElement to highlight the HTML element
                        RectangleElement highlightRectangle = new RectangleElement(pdfRectangleInPage.X, pdfRectangleInPage.Y,
                            pdfRectangleInPage.Width, pdfRectangleInPage.Height);
                        highlightRectangle.ForeColor = Color.Green;

                        pdfPage.AddElement(highlightRectangle);
                    }
                }

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

                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;
            }
        }
        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 the bookmarks when the document is opened
                pdfConverter.PdfViewerPreferences.PageMode = ViewerPageMode.UseOutlines;

                // set top and bottom page margins
                pdfConverter.PdfDocumentOptions.TopMargin = 5;
                pdfConverter.PdfDocumentOptions.BottomMargin = 5;

                // Inform the converter about the HTML elements for which we want the location in PDF
                // In this sample we want the location of the entries in the Table of Contents
                // The HTML ID of each entry in the table of contents is of form TOCEntry_{EntryIndex}_ID
                // the HTML ID of each target of a table of contents entry is of form TOCEntry_{EntryIndex}_Target_ID

                // Both toc entries and toc entries targets locations in PDF will be retrieved
                // and therefore the number of IDs is twice TOC entries number
                pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors = new string[2 * TOC_ENTRIES_COUNT];

                int mappingsTableIdx = 0;
                for (int tocEntryIndex = 1; tocEntryIndex <= TOC_ENTRIES_COUNT; tocEntryIndex++)
                {
                    // add the HTML ID of the TOC entry element to the list of elements for which we want the PDF location
                    string tocEntryID = String.Format("#TOCEntry_{0}_ID", tocEntryIndex);
                    pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors[mappingsTableIdx++] = tocEntryID;

                    // add the HTML ID of the TOC entry target element to the list of elements for which we want the PDF location
                    string tocEntryTargetID = String.Format("#TOCEntry_{0}_Target_ID", tocEntryIndex);
                    pdfConverter.HtmlElementsMappingOptions.HtmlElementSelectors[mappingsTableIdx++] = tocEntryTargetID;
                }

                // set bookmark options
                pdfConverter.PdfBookmarkOptions.HtmlElementSelectors = new string[] { "A[class=\"bookmark\"]" };

                // the URL of the HTML document to convert
                string htmlBookFilePath = System.IO.Path.Combine(Application.StartupPath, @"..\..\HtmlBook\Book.htm");

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

                // Create a font used to write the page numbers in the table of contents
                PdfFont pageNumberFont = pdfDocument.Fonts.Add(new Font("Arial", PAGE_NUMBER_FONT_SIZE, FontStyle.Bold, GraphicsUnit.Point), true);

                // get the right edge of the table of contents where to position the page numbers
                float tocEntryMaxRight = 0.0f;
                for (int tocEntryIdx = 1; tocEntryIdx <= TOC_ENTRIES_COUNT; tocEntryIdx++)
                {
                    string tocEntryID = String.Format("TOCEntry_{0}_ID", tocEntryIdx);
                    HtmlElementMapping tocEntryLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryID);
                    if (tocEntryLocation.PdfRectangles[0].Rectangle.Right > tocEntryMaxRight)
                        tocEntryMaxRight = tocEntryLocation.PdfRectangles[0].Rectangle.Right;
                }

                // Add page number for each entry in the table of contents
                for (int tocEntryIdx = 1; tocEntryIdx <= TOC_ENTRIES_COUNT; tocEntryIdx++)
                {
                    string tocEntryID = String.Format("TOCEntry_{0}_ID", tocEntryIdx);
                    string tocEntryTargetID = String.Format("TOCEntry_{0}_Target_ID", tocEntryIdx);

                    HtmlElementMapping tocEntryLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryID);
                    HtmlElementMapping tocEntryTargetLocation = pdfConverter.HtmlElementsMappingOptions.HtmlElementsMappingResult.GetElementByHtmlId(tocEntryTargetID);

                    // get the TOC entry page and bounds
                    PdfPage tocEntryPdfPage = pdfDocument.Pages[tocEntryLocation.PdfRectangles[0].PageIndex];
                    RectangleF tocEntryPdfRectangle = tocEntryLocation.PdfRectangles[0].Rectangle;

                    // get the page number of target where the TOC entry points
                    int tocEntryTargetPageNumber = tocEntryTargetLocation.PdfRectangles[0].PageIndex + 1;

                    // add dashed line from text entry to the page number
                    LineElement lineToNumber = new LineElement(tocEntryPdfRectangle.Right + 5, tocEntryPdfRectangle.Y + tocEntryPdfRectangle.Height / 2,
                            tocEntryMaxRight + 80, tocEntryPdfRectangle.Y + tocEntryPdfRectangle.Height / 2);
                    lineToNumber.LineStyle.LineWidth = 1;
                    lineToNumber.LineStyle.LineDashStyle = LineDashStyle.Dash;
                    lineToNumber.ForeColor = Color.Green;
                    tocEntryPdfPage.AddElement(lineToNumber);

                    // create the page number text element to the right of the TOC entry
                    TextElement pageNumberTextEement = new TextElement(tocEntryMaxRight + 85, tocEntryPdfRectangle.Y, -1, tocEntryPdfRectangle.Height,
                            tocEntryTargetPageNumber.ToString(), pageNumberFont);
                    pageNumberTextEement.TextAlign = HorizontalTextAlign.Left;
                    pageNumberTextEement.VerticalTextAlign = VerticalTextAlign.Middle;
                    pageNumberTextEement.ForeColor = Color.Blue;

                    // add the page number to the right of the TOC entry
                    tocEntryPdfPage.AddElement(pageNumberTextEement);
                }

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

                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;
            }
        }