EVO HTML to PDF Converter

Getting Started with EVO PDF Client for UWP

EVO PDF Client for Universal Windows Platform Documentation

EVO HTML to PDF Converter Client for Universal Windows Platform allows you to easily convert in just a few lines of code HTML pages and HTML strings to PDF. In this section you can learn about the basic settings of the converter.

The HTML to PDF Converter object of HtmlToPdfConverter type can be initialized with the TCP/IP address of the server or with the HTTP URL address of the server, function of the HTML to PDF Server type you have installed.

You can also choose the HTML document to convert which can be:

The basic options you can set are grouped in a few categories.

HTML Viewer Options

  • HTML Viewer Width. This option is the equivalent in converter of the browser window width. The property you can set in your code to control the browser window width is HtmlToPdfConverterHtmlViewerWidth. When the browser window width is changed the HTML content displayed inside the window can have a different layout and something similar happens when you change the HTML Viewer width of the converter. At a given viewer width, the converter will capture by default the whole height of the HTML content, but you can set the HTML Viewer height to capture only the top part of the HTML page

  • HTML Viewer Height. This option is the equivalent in converter of the browser window height and can be used to limit the conversion to the top part of the HTML page. If this property is not set the entire page will be converted. The property you can set in your code to control the browser window height is HtmlToPdfConverterHtmlViewerHeight

PDF Page Options

Navigation Options

Code Sample - Convert a HTML Page or a HTML String to PDF using HtmlToPdfConverter Class

C#
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Runtime.InteropServices.WindowsRuntime;
using Windows.Foundation;
using Windows.Foundation.Collections;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Controls.Primitives;
using Windows.UI.Xaml.Data;
using Windows.UI.Xaml.Input;
using Windows.UI.Xaml.Media;
using Windows.UI.Xaml.Navigation;

using System.Threading.Tasks;
using Windows.UI.Popups;
using Windows.Storage;

// Use EVO PDF Namespace
using EvoPdf.HtmlToPdfClient;

namespace EvoHtmlToPdfClientDemo
{
    /// <summary>
    /// An empty page that can be used on its own or navigated to within a Frame.
    /// </summary>
    public sealed partial class MainPage : Page
    {
        public MainPage()
        {
            this.InitializeComponent();
        }

        private object pendingConversionSync = new object();
        bool pendingConversion = false;

        private async void ButtonConvertUrlToPdf_Click(object sender, RoutedEventArgs e)
        {
            // If another conversion is in progress the ignore current request
            bool ignoreRequest = false;
            lock (pendingConversionSync)
            {
                if (pendingConversion)
                    ignoreRequest = true;
                else
                {
                    msgUrlToPdfInProgress.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    pendingConversion = true;
                }
            }

            if (ignoreRequest)
                return;

            try
            {
                String serverIP = textBoxServerIP.Text;
                uint port = uint.Parse(textBoxServerPort.Text);

                HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(serverIP, port);

                // set license key
                htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";

                // set service password if necessary
                if (textBoxServicePassword.Text.Length > 0)
                    htmlToPdfConverter.ServicePassword = textBoxServicePassword.Text;

                // set HTML viewer width
                htmlToPdfConverter.HtmlViewerWidth = int.Parse(textBoxHtmlViewerWidth.Text);

                // set HTML viewer height if necessary
                if (textBoxHtmlViewerHeight.Text.Length > 0)
                    htmlToPdfConverter.HtmlViewerHeight = int.Parse(textBoxHtmlViewerHeight.Text);

                // set navigation timeout
                htmlToPdfConverter.NavigationTimeout = int.Parse(textBoxHtmlViewerWidth.Text);

                // set conversion delay if necessary
                if (textBoxConversionDelay.Text.Length > 0)
                    htmlToPdfConverter.ConversionDelay = int.Parse(textBoxConversionDelay.Text);

                // set PDF page size
                htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = SelectedPdfPageSize();

                // set PDF page orientation
                htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = SelectedPdfPageOrientation();

                // set margins
                htmlToPdfConverter.PdfDocumentOptions.LeftMargin = int.Parse(textBoxLeftMargin.Text);
                htmlToPdfConverter.PdfDocumentOptions.RightMargin = int.Parse(textBoxRightMargin.Text);
                htmlToPdfConverter.PdfDocumentOptions.TopMargin = int.Parse(textBoxTopMargin.Text);
                htmlToPdfConverter.PdfDocumentOptions.BottomMargin = int.Parse(textBoxBottomMargin.Text);

                // add header
                if (checkBoxAddHeader.IsChecked != null && (bool)checkBoxAddHeader.IsChecked)
                {
                    htmlToPdfConverter.PdfDocumentOptions.ShowHeader = true;
                    DrawHeader(htmlToPdfConverter, true);
                }

                // add footer
                if (checkBoxAddFooter.IsChecked != null && (bool)checkBoxAddFooter.IsChecked)
                {
                    htmlToPdfConverter.PdfDocumentOptions.ShowFooter = true;
                    DrawFooter(htmlToPdfConverter, true, true);
                }

                string urlToConvert = textBoxUrl.Text;
                string errorMessage = null;

                // Convert the HTML page from give URL to PDF in a buffer
                byte[] pdfBytes = await Task.Run<byte[]>(() =>
                {
                    byte[] resultBytes = null;
                    try
                    {
                        resultBytes = htmlToPdfConverter.ConvertUrl(urlToConvert);
                    }
                    catch (Exception ex)
                    {
                        errorMessage = String.Format("Conversion failed. {0}", ex.Message);
                        return null;
                    }

                    return resultBytes;
                });

                if (pdfBytes == null)
                {
                    MessageDialog errorMessageDialog = new MessageDialog(errorMessage, "Conversion failed");
                    await errorMessageDialog.ShowAsync();
                    return;
                }

                // Save the PDF in a file
                Windows.Storage.StorageFolder installedLocation = Windows.Storage.ApplicationData.Current.LocalFolder;
                StorageFile outStorageFile = installedLocation.CreateFileAsync("EvoHtmlToPdf.pdf", CreationCollisionOption.ReplaceExisting).AsTask().Result;
                FileIO.WriteBytesAsync(outStorageFile, pdfBytes).AsTask().Wait();

                // Open the file in a PDF viewer
                await Windows.System.Launcher.LaunchFileAsync(outStorageFile);
            }
            finally
            {
                lock (pendingConversionSync)
                {
                    msgUrlToPdfInProgress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    pendingConversion = false;
                }
            }
        }

        private async void ButtonConvertHtmlToPdf_Click(object sender, RoutedEventArgs e)
        {
            // If another conversion is in progress the ignore current request
            bool ignoreRequest = false;
            lock (pendingConversionSync)
            {
                if (pendingConversion)
                    ignoreRequest = true;
                else
                {
                    msgHtmlToPdfInProgress.Visibility = Windows.UI.Xaml.Visibility.Visible;
                    pendingConversion = true;
                }
            }

            if (ignoreRequest)
                return;

            try
            {
                String serverIP = textBoxServerIP.Text;
                uint port = uint.Parse(textBoxServerPort.Text);

                HtmlToPdfConverter htmlToPdfConverter = new HtmlToPdfConverter(serverIP, port);

                // set license key
                htmlToPdfConverter.LicenseKey = "4W9+bn19bn5ue2B+bn1/YH98YHd3d3c=";

                // set service password if necessary
                if (textBoxServicePassword.Text.Length > 0)
                    htmlToPdfConverter.ServicePassword = textBoxServicePassword.Text;

                // set HTML viewer width
                htmlToPdfConverter.HtmlViewerWidth = int.Parse(textBoxHtmlViewerWidth.Text);

                // set HTML viewer height if necessary
                if (textBoxHtmlViewerHeight.Text.Length > 0)
                    htmlToPdfConverter.HtmlViewerHeight = int.Parse(textBoxHtmlViewerHeight.Text);

                // set navigation timeout
                htmlToPdfConverter.NavigationTimeout = int.Parse(textBoxHtmlViewerWidth.Text);

                // set conversion delay if necessary
                if (textBoxConversionDelay.Text.Length > 0)
                    htmlToPdfConverter.ConversionDelay = int.Parse(textBoxConversionDelay.Text);

                // set PDF page size
                htmlToPdfConverter.PdfDocumentOptions.PdfPageSize = SelectedPdfPageSize();

                // set PDF page orientation
                htmlToPdfConverter.PdfDocumentOptions.PdfPageOrientation = SelectedPdfPageOrientation();

                // set margins
                htmlToPdfConverter.PdfDocumentOptions.LeftMargin = int.Parse(textBoxLeftMargin.Text);
                htmlToPdfConverter.PdfDocumentOptions.RightMargin = int.Parse(textBoxRightMargin.Text);
                htmlToPdfConverter.PdfDocumentOptions.TopMargin = int.Parse(textBoxTopMargin.Text);
                htmlToPdfConverter.PdfDocumentOptions.BottomMargin = int.Parse(textBoxBottomMargin.Text);

                // add header
                if (checkBoxAddHeader.IsChecked != null && (bool)checkBoxAddHeader.IsChecked)
                {
                    htmlToPdfConverter.PdfDocumentOptions.ShowHeader = true;
                    DrawHeader(htmlToPdfConverter, true);
                }

                // add footer
                if (checkBoxAddFooter.IsChecked != null && (bool)checkBoxAddFooter.IsChecked)
                {
                    htmlToPdfConverter.PdfDocumentOptions.ShowFooter = true;
                    DrawFooter(htmlToPdfConverter, true, true);
                }

                string htmlStringToConvert = textBoxHtml.Text;
                string baseUrl = textBoxBaseUrl.Text;

                string errorMessage = null;

                // Convert the HTML page from give URL to PDF in a buffer
                byte[] pdfBytes = await Task.Run<byte[]>(() =>
                {
                    byte[] resultBytes = null;
                    try
                    {
                        resultBytes = htmlToPdfConverter.ConvertHtml(htmlStringToConvert, baseUrl);
                    }
                    catch (Exception ex)
                    {
                        errorMessage = String.Format("Conversion failed. {0}", ex.Message);
                        return null;
                    }

                    return resultBytes;
                });

                if (pdfBytes == null)
                {
                    MessageDialog errorMessageDialog = new MessageDialog(errorMessage, "Conversion failed");
                    await errorMessageDialog.ShowAsync();
                    return;
                }

                // Save the PDF in a file
                Windows.Storage.StorageFolder installedLocation = Windows.Storage.ApplicationData.Current.LocalFolder;
                StorageFile outStorageFile = installedLocation.CreateFileAsync("EvoHtmlToPdf.pdf", CreationCollisionOption.ReplaceExisting).AsTask().Result;
                FileIO.WriteBytesAsync(outStorageFile, pdfBytes).AsTask().Wait();

                // Open the file in a PDF viewer
                await Windows.System.Launcher.LaunchFileAsync(outStorageFile);
            }
            finally
            {
                lock (pendingConversionSync)
                {
                    msgHtmlToPdfInProgress.Visibility = Windows.UI.Xaml.Visibility.Collapsed;
                    pendingConversion = false;
                }
            }
        }

        private void DrawHeader(HtmlToPdfConverter htmlToPdfConverter, bool drawHeaderLine)
        {
            String headerHtmlString =
                "<!DOCTYPE html>" +
                "<html>" +
                "<head>" +
                    "<title>HTML in Header</title>" +
                "</head>" +
                "<body style=\"font-family: 'Times New Roman'; font-size: 14px\">" +
                    "<table>" +
                        "<tr>" +
                            "<td style=\"font-weight: bold; color: navy\">HTML in Header</td>" +
                        "</tr>" +
                        "<tr>" +
                            "<td>" +
                                "<a href=\"http://www.evopdf.com\">" +
                                    "<img alt=\"Logo Image\" style=\"width: 200px\" src=\"http://www.evopdf.com/images/evopdf_logo.jpg\" /></a>" +
                            "</td>" +
                        "</tr>" +
                    "</table>" +
                "</body>" +
                "</html>";

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

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

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

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

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

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

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

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

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

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

            htmlToPdfConverter.PdfHeaderOptions.ShowInFirstPage = checkBoxShowInFirstPage != null && (bool)checkBoxShowInFirstPage.IsChecked;

        }

        private void DrawFooter(HtmlToPdfConverter htmlToPdfConverter, bool addPageNumbers, bool drawFooterLine)
        {
            String footerHtmlString =
                    "<!DOCTYPE html>" +
                    "<html>" +
                    "<head>" +
                        "<title>HTML in Footer</title>" +
                    "</head>" +
                    "<body style=\"font-family: 'Times New Roman'; font-size: 14px\">" +
                        "<table>" +
                            "<tr>" +
                                "<td style=\"font-weight: bold; color: green\">HTML in Footer</td>" +
                            "</tr>" +
                            "<tr>" +
                                "<td>" +
                                    "<a href=\"http://www.evopdf.com\">" +
                                        "<img alt=\"Logo Image\" style=\"width: 200px\" src=\"http://www.evopdf.com/images/evopdf_logo.jpg\" /></a>" +
                                "</td>" +
                            "</tr>" +
                        "</table>" +
                    "</body>" +
                    "</html>";

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            htmlToPdfConverter.PdfFooterOptions.ShowInFirstPage = checkBoxShowInFirstPage != null && (bool)checkBoxShowInFirstPage.IsChecked;
        }

        private PdfPageSize SelectedPdfPageSize()
        {
            string selectedValue = (string)((ListBoxItem)comboBoxPageSize.SelectedValue).Content;

            switch (selectedValue)
            {
                case "A0":
                    return PdfPageSize.A0;
                case "A1":
                    return PdfPageSize.A1;
                case "A10":
                    return PdfPageSize.A10;
                case "A2":
                    return PdfPageSize.A2;
                case "A3":
                    return PdfPageSize.A3;
                case "A4":
                    return PdfPageSize.A4;
                case "A5":
                    return PdfPageSize.A5;
                case "A6":
                    return PdfPageSize.A6;
                case "A7":
                    return PdfPageSize.A7;
                case "A8":
                    return PdfPageSize.A8;
                case "A9":
                    return PdfPageSize.A9;
                case "ArchA":
                    return PdfPageSize.ArchA;
                case "ArchB":
                    return PdfPageSize.ArchB;
                case "ArchC":
                    return PdfPageSize.ArchC;
                case "ArchD":
                    return PdfPageSize.ArchD;
                case "ArchE":
                    return PdfPageSize.ArchE;
                case "B0":
                    return PdfPageSize.B0;
                case "B1":
                    return PdfPageSize.B1;
                case "B2":
                    return PdfPageSize.B2;
                case "B3":
                    return PdfPageSize.B3;
                case "B4":
                    return PdfPageSize.B4;
                case "B5":
                    return PdfPageSize.B5;
                case "Flsa":
                    return PdfPageSize.Flsa;
                case "HalfLetter":
                    return PdfPageSize.HalfLetter;
                case "Ledger":
                    return PdfPageSize.Ledger;
                case "Legal":
                    return PdfPageSize.Legal;
                case "Letter":
                    return PdfPageSize.Letter;
                case "Letter11x17":
                    return PdfPageSize.Letter11x17;
                case "Note":
                    return PdfPageSize.Note;
                default:
                    return PdfPageSize.A4;
            }
        }

        private PdfPageOrientation SelectedPdfPageOrientation()
        {
            string selectedValue = (string)((ListBoxItem)comboBoxPageOrientation.SelectedValue).Content;

            return (selectedValue == "Portrait") ? PdfPageOrientation.Portrait : PdfPageOrientation.Landscape;
        }
    }
}