Search code examples
asp.netpdf-conversionwinnovative

Winnovative, PdfConverter Setting the Header and Footer height dynamicaly


I am using the Winnovative's PdfConverter to convert my HTML page to a PDF, i am able to get the PDF with header footer and all. But i have a requirement where i need to set the height of the Header and footer dynamically based on the content of the text that needs to be added. Below is the code i tried to achieve this but was not successful. Please can you help on what would i be missing here, or is there any other method i need to follow. The PdfFooterOptions.FooterHeight is initially set to default 40px.

                PdfConverter pdfConverter = new PdfConverter();

                // set the converter options
                pdfConverter.PdfDocumentOptions.PdfPageSize = PdfPageSize.A4;
                pdfConverter.PdfDocumentOptions.PdfCompressionLevel = PdfCompressionLevel.Normal;
                pdfConverter.PdfDocumentOptions.PdfPageOrientation = PdfPageOrientation.Portrait;

                // set header and footer
                pdfConverter.PdfDocumentOptions.ShowHeader = true;
                pdfConverter.PdfDocumentOptions.ShowFooter = true;

                //Add header and footer text

                AddHeaderElements(pdfConverter, text);
                AddFooterElements(pdfConverter, text);
                // set the HTML content
                pdfConverter.PdfDocumentOptions.FitWidth = true;
                // set the embedded fonts option
                pdfConverter.PdfDocumentOptions.EmbedFonts = true;
                // set the live HTTP links option
                pdfConverter.PdfDocumentOptions.LiveUrlsEnabled = true;
                // set the JavaScript
                pdfConverter.JavaScriptEnabled = true;
                // set the images in PDF are compressed with JPEG to reduce the PDF document size
                pdfConverter.PdfDocumentOptions.JpegCompressionEnabled = true;
                // enable auto-generated bookmarks for a specified list of tags (e.g. H1 and H2)
                pdfConverter.PdfBookmarkOptions.HtmlElementSelectors = new string[] { "H1", "H2" };
                // Performs the conversion and get the pdf document bytes that can be further 
                // saved to a file or sent as response to browser
                // The baseURL parameter helps the converter to get the CSS files and images
                // referenced by a relative URL in the HTML string.  
                byte[] pdfValue = null;
                pdfValue = pdfConverter.GetPdfBytesFromHtmlString(htmlCodeToConvert);



    private void AddFooterElements(PdfConverter pdfConverter, string title)
    {
        //write the page number
        TextElement footerText = new TextElement(550, pdfConverter.PdfFooterOptions.FooterHeight - 20,
                    string.Format(uiContentController.GetText("Aanvarag_Page"), "&p;", "&P;"),
                    new System.Drawing.Font(new System.Drawing.FontFamily("Tahoma"),
                    7, System.Drawing.GraphicsUnit.Point));
        footerText.EmbedSysFont = true;
        footerText.TextAlign = HorizontalTextAlign.Left;
        pdfConverter.PdfFooterOptions.AddElement(footerText);

        // set the footer HTML area
        HtmlToPdfElement footerHtml = new HtmlToPdfElement(10, 0, 0,
                    0,
                    title, null, 1024, 0);

        footerHtml.NavigationCompletedEvent += OnFooterHtmlNavigationCompleted;

        pdfConverter.PdfFooterOptions.AddElement(footerHtml);
    }

    void OnFooterHtmlNavigationCompleted(NavigationCompletedParams eventParams)
    {
        // Get the header HTML width and height from event parameters
        float footerHtmlWidth = eventParams.HtmlContentWidthPt;
        float footerHtmlHeight = eventParams.HtmlContentHeightPt;

        // Calculate the header width from coverter settings
        float footerWidth = pdfConverter.PdfDocumentOptions.PdfPageSize.Width - pdfConverter.PdfDocumentOptions.LeftMargin -
                    pdfConverter.PdfDocumentOptions.RightMargin;

        // Calculate a resize factor to fit the header width
        float resizeFactor = 1;
        if (footerHtmlWidth > footerWidth)
            resizeFactor = footerWidth / footerHtmlWidth;

        // Calculate the header height to preserve the HTML aspect ratio
        float footerHeight = footerHtmlHeight * resizeFactor;

        // Set the calculated header height
        pdfConverter.PdfFooterOptions.FooterHeight = footerHeight;
    }

Solution

  • There is a working example with source code for headers. For footers should be similar.

    // Define the HTML to PDF converter object as a class member to make it accessible in the headerHtml_NavigationCompletedEvent handler
    // where the header height will be automatically adjusted
    private HtmlToPdfConverter htmlToPdfConverter;
    
    // Indicates if a line should be drawn at the botom of the header
    private bool drawHeaderLine = true;
    
    protected void convertToPdfButton_Click(object sender, EventArgs e)
    {
        // Create a HTML to PDF converter object with default settings
        htmlToPdfConverter = new HtmlToPdfConverter();
    
        // Set license key received after purchase to use the converter in licensed mode
        // Leave it not set to use the converter in demo mode
        htmlToPdfConverter.LicenseKey = "fvDh8eDx4fHg4P/h8eLg/+Dj/+jo6Og=";
    
        // Enable header in the generated PDF document
        htmlToPdfConverter.PdfDocumentOptions.ShowHeader = true;
    
        string headerHtmlUrl = Server.MapPath("~/DemoAppFiles/Input/HTML_Files/Header_HTML.html");
        Document documentObject = null;
        try
        {
            if (autoResizeHeaderRadioButton.Checked)
            {
                // Create a HTML element to be added in header
                HtmlToPdfElement headerHtml = new HtmlToPdfElement(headerHtmlUrl);
    
                // Install a handler where to set the automatically calculated header height
                headerHtml.NavigationCompletedEvent += new NavigationCompletedDelegate(headerHtml_NavigationCompletedEvent);
    
                // Add the HTML element to header
                // When the element is rendered in header by converter, the headerHtml_NavigationCompletedEvent handler 
                // will be invoked and the header height will be automatically calculated
                htmlToPdfConverter.PdfHeaderOptions.AddElement(headerHtml);
    
                // Call the converter to produce a Document object
                documentObject = htmlToPdfConverter.ConvertUrlToPdfDocumentObject(urlTextBox.Text);
    
                // Uninstall the handler
                headerHtml.NavigationCompletedEvent -= new NavigationCompletedDelegate(headerHtml_NavigationCompletedEvent);
    
                // Draw a line at the header bottom
                if (drawHeaderLine)
                {
                    float headerWidth = documentObject.Header.Width;
                    float headerHeight = documentObject.Header.Height;
    
                    // Create a line element for the bottom of the header
                    LineElement headerLine = new LineElement(0, headerHeight - 1, headerWidth, headerHeight - 1);
    
                    // Set line color
                    headerLine.ForeColor = Color.Gray;
    
                    // Add line element to the bottom of the header
                    documentObject.Header.AddElement(headerLine);
                }
    
                // Save the PDF document in a memory buffer
                byte[] outPdfBuffer = documentObject.Save();
    
                // Send the PDF as response to browser
    
                // Set response content type
                Response.AddHeader("Content-Type", "application/pdf");
    
                // Instruct the browser to open the PDF file as an attachment or inline
                Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Auto_Resize_Header_Footer.pdf; size={0}", outPdfBuffer.Length.ToString()));
    
                // Write the PDF document buffer to HTTP response
                Response.BinaryWrite(outPdfBuffer);
    
                // End the HTTP response and stop the current page processing
                Response.End();
            }
            else
            {
                // Create a HTML to PDF element to be added in header
                HtmlToPdfElement headerHtml = new HtmlToPdfElement(headerHtmlUrl);
    
                // Set a fixed header height in points
                htmlToPdfConverter.PdfHeaderOptions.HeaderHeight = float.Parse(headerHeightTextBox.Text);
    
                // Set the HTML element to fit the container height
                headerHtml.FitHeight = true;
    
                // Add HTML element to fit the fixed header height
                htmlToPdfConverter.PdfHeaderOptions.AddElement(headerHtml);
    
                // Draw a line at the header bottom
                if (drawHeaderLine)
                {
                    // Calculate the header width based on PDF page size and margins
                    float headerWidth = htmlToPdfConverter.PdfDocumentOptions.PdfPageSize.Width -
                                htmlToPdfConverter.PdfDocumentOptions.LeftMargin - htmlToPdfConverter.PdfDocumentOptions.RightMargin;
    
                    // Calculate header height
                    float headerHeight = htmlToPdfConverter.PdfHeaderOptions.HeaderHeight;
    
                    // Create a line element for the bottom of the header
                    LineElement headerLine = new LineElement(0, headerHeight - 1, headerWidth, headerHeight - 1);
    
                    // Set line color
                    headerLine.ForeColor = Color.Gray;
    
                    // Add line element to the bottom of the header
                    htmlToPdfConverter.PdfHeaderOptions.AddElement(headerLine);
                }
    
                // Convert the HTML page to a PDF document in a memory buffer
                byte[] outPdfBuffer = htmlToPdfConverter.ConvertUrl(urlTextBox.Text);
    
                // Send the PDF as response to browser
    
                // Set response content type
                Response.AddHeader("Content-Type", "application/pdf");
    
                // Instruct the browser to open the PDF file as an attachment or inline
                Response.AddHeader("Content-Disposition", String.Format("attachment; filename=Auto_Resize_Header_Footer.pdf; size={0}", outPdfBuffer.Length.ToString()));
    
                // Write the PDF document buffer to HTTP response
                Response.BinaryWrite(outPdfBuffer);
    
                // End the HTTP response and stop the current page processing
                Response.End();
            }
        }
        finally
        {
            // Close the PDF document
            if (documentObject != null)
                documentObject.Close();
        }
    }
    
    /// <summary>
    /// This handler is called after the navigation to header HTML completed. The document header is resized in this event handler
    /// </summary>
    /// <param name="eventParams">The event parameter containing the HTML content size in pixels and points</param>
    void headerHtml_NavigationCompletedEvent(NavigationCompletedParams eventParams)
    {
        // Get the header HTML width and height from event parameters
        float headerHtmlWidth = eventParams.HtmlContentWidthPt;
        float headerHtmlHeight = eventParams.HtmlContentHeightPt;
    
        // Calculate the header width from coverter settings
        float headerWidth = htmlToPdfConverter.PdfDocumentOptions.PdfPageSize.Width - htmlToPdfConverter.PdfDocumentOptions.LeftMargin -
                    htmlToPdfConverter.PdfDocumentOptions.RightMargin;
    
        // Calculate a resize factor to fit the header width
        float resizeFactor = 1;
        if (headerHtmlWidth > headerWidth)
            resizeFactor = headerWidth / headerHtmlWidth;
    
        // Calculate the header height to preserve the HTML aspect ratio
        float headerHeight = headerHtmlHeight * resizeFactor;
    
        if (!(headerHeight < htmlToPdfConverter.PdfDocumentOptions.PdfPageSize.Height - htmlToPdfConverter.PdfDocumentOptions.TopMargin -
                    htmlToPdfConverter.PdfDocumentOptions.BottomMargin))
        {
            throw new Exception("The header height cannot be bigger than PDF page height");
        }
    
        // Set the calculated header height
        htmlToPdfConverter.PdfDocumentOptions.DocumentObject.Header.Height = headerHeight;
    }