This example demonstrates how to convert HTML file/Url to a PDF file using simple settings. Click on About to see full description of the example.
Our HTML to PDF Converter library adds the ability to convert HTML pages and text to PDF documents with as little as 5 lines of code. In this example we explore some basic options of the converter as follows:
You can choose the source of HTML by clicking on "Convert URL or local file" or "Convert HTML string":
- Webpage URL or local file path: The URL to the webpage or local file to convert to PDF. If authentication is needed or you are behind a proxy server, you will need to set the converter proxy options as illustrated in our documentation.
- HTML text: The HTML text to be converted to PDF. This conversion mode also lets you specify the Base URL for the HTML text. That Base URL is used to resolve the relative URLs found in the HTML text to absolute URLs. You can omit this parameter when your HTML text does not include any relative URLs.
Viewport Settings
- Viewport Width: This is the width of the virtual browser window in pixels used in our converter. When you change the Viewport width, the content in the window may have different layout, resulting in a different PDF output.
- Viewport Height: This is the height of the virtual browser window in pixels. When set to 0, the converter will use default value of 768px. If you set this value large enough the converter will capture the whole webpage. It can also be used to limit the part of the webpage you want to convert.
PDF Page Settings
- PDF Page Size: This specifies the size of the page in the converted PDF document. In this example, we include several standard page sizes like A4, B3, Letter, etc. The page size can be changed to custom values in points (1 points = 1/72 inches).
- Page Orientation: Orientation of PDF page can be set to Portrait or Landscape. By default the page orientation is Portrait
Misc Settings
- Conversion Delay: This is the amount of time, in ms, the converter waits for the webpage to load before rendering it. There are several options for the conversion delay in WaitMode property including: Delay, DocumentReady and Manual. Delay mode lets you specify how long the converter waits before converting. DocumentReady mode instructs the converter to wait until the document is read. It's similar to $(document).ready() event in jQuery. Manual let you trigger the conversion manually by calling Javascript method named officePdfReady. You can specify whether to wait for all the conditions to meet before triggering the conversion or wait for one of them only in option UseOrOperatorInWaitMode.
- Timeout: This is the amount of time, in ms, the converter waits for the page to load before returning timed out exception.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.Drawing.Imaging;
using System.Drawing.Printing;
using System.IO;
using System.Text;
using System.Threading.Tasks;
using System.Threading;
#if !WEB
using System.Windows.Forms;
#else
using System.Web.UI;
using System.Web.UI.WebControls;
#endif
using OfficeComponent.HtmlToPdf;
namespace OfficeComponent.Samples
{
partial class HtmlToPdfBasicExample : ExampleBase
#if WEB
, IUIExample
#endif
{
// Options
public bool ConvertUrl { get; set; }
public string Url { get; set; }
public string HtmlString { get; set; }
public string HtmlStringBaseUrl { get; set; }
public int Width { get; set; }
public int Height { get; set; }
public OfficeComponent.HtmlToPdf.PageSize PageSize { get; set; }
public bool Portrait { get; set; }
public OfficeComponent.HtmlToPdf.PageMargins Margin { get; set; }
public int ConversionDelay { get; set; }
public int Timeout { get; set; }
public bool SinglePage { get; set; }
public EventHandler Progress;
#if WEB
public HtmlToPdfBasicExample() : base(null,null)
{
}
#endif
public HtmlToPdfBasicExample(string commonDataPath, string outputDir)
: base(commonDataPath, outputDir)
{
}
public HtmlToPdfBasicExample(string commonDataPath, string outputDir, string xmlFile)
: base(commonDataPath, outputDir, xmlFile)
{
}
Action onComplete;
Action onError;
string outputPath;
public void ExecuteAsync(Action onComplete, Action onError)
{
if (Width <= 0 || Height <= 0)
{
ShowError("Invalid Width or Height");
onComplete(null);
return;
}
if (ConversionDelay < 0)
{
ShowError("Invalid conversion delay");
onComplete(null);
return;
}
// Set output path.
outputPath = Path.Combine(OutputDir, this.GetType().Name + ".pdf");
if (File.Exists(outputPath))
File.Delete(outputPath);
// Create a new converter.
var c = new HtmlToPdfConverter()
{
ViewportWidth = Width,
ViewportHeight = Height,
PageSize = PageSize,
PageMargin = Margin,
Portrait = Portrait,
Delay = ConversionDelay,
Timeout = Timeout,
SinglePage = SinglePage
};
if (Progress != null)
c.Progress += Progress;
this.onComplete = onComplete;
this.onError = onError;
if (ConvertUrl)
{
if (string.IsNullOrWhiteSpace(Url))
{
ShowError("Please specify the URL to convert.");
onComplete(null);
return;
}
// Convert URL
c.ConvertAsync(Url, outputPath, OnConversionComplete);
}
else
{
if (string.IsNullOrWhiteSpace(HtmlString))
{
ShowError("Please specify the HTML string to convert.");
onComplete(null);
return;
}
// Convert the specified HTML string.
c.ConvertStringAsync(HtmlString, HtmlStringBaseUrl, outputPath, OnConversionComplete);
}
}
void OnConversionComplete(object sender, AsyncCompletedEventArgs e)
{
if (e.Error != null)
onError(e.Error);
else
onComplete(outputPath);
}
public override string Execute()
{
if (Width <= 0 || Height < 0)
{
ShowError("Invalid Width or Height");
return null;
}
if (ConversionDelay < 0)
{
ShowError("Invalid conversion delay");
return null;
}
// Set output path.
var outputPath = Path.Combine(OutputDir, this.GetType().Name + ".pdf");
if (File.Exists(outputPath))
File.Delete(outputPath);
// Create a new converter.
var c = new HtmlToPdfConverter()
{
ViewportWidth = Width,
ViewportHeight = Height,
PageSize = PageSize,
PageMargin = Margin,
Portrait = Portrait,
Delay = ConversionDelay,
Timeout = Timeout,
SinglePage = SinglePage
};
if (Progress != null)
c.Progress += Progress;
try
{
if (ConvertUrl)
{
if (string.IsNullOrWhiteSpace(Url))
{
ShowError("Please specify the URL to convert.");
return null;
}
// Convert URL
c.Convert(Url, outputPath);
}
else
{
if (string.IsNullOrWhiteSpace(HtmlString))
{
ShowError("Please specify the HTML string to convert.");
return null;
}
// Convert the specified HTML string.
c.ConvertString(HtmlString, HtmlStringBaseUrl, outputPath);
}
}
catch (Exception ex)
{
ShowError(ex.Message);
}
return outputPath;
}
}
}
Imports System.ComponentModel
Imports System.Drawing.Imaging
Imports System.Drawing.Printing
Imports System.IO
Imports System.Text
Imports System.Threading.Tasks
Imports System.Threading
#If Not WEB Then
#Else
Imports System.Web.UI
Imports System.Web.UI.WebControls
#End If
Imports OfficeComponent.HtmlToPdf
Namespace OfficeComponent.Samples
#If WEB Then
Partial Friend Class HtmlToPdfBasicExample
Inherits ExampleBase
Implements IUIExample
#Else
Partial Friend Class HtmlToPdfBasicExample
Inherits ExampleBase
#End If
' Options
Private privateConvertUrl As Boolean
Public Property ConvertUrl() As Boolean
Get
Return privateConvertUrl
End Get
Set(ByVal value As Boolean)
privateConvertUrl = value
End Set
End Property
Private privateUrl As String
Public Property Url() As String
Get
Return privateUrl
End Get
Set(ByVal value As String)
privateUrl = value
End Set
End Property
Private privateHtmlString As String
Public Property HtmlString() As String
Get
Return privateHtmlString
End Get
Set(ByVal value As String)
privateHtmlString = value
End Set
End Property
Private privateHtmlStringBaseUrl As String
Public Property HtmlStringBaseUrl() As String
Get
Return privateHtmlStringBaseUrl
End Get
Set(ByVal value As String)
privateHtmlStringBaseUrl = value
End Set
End Property
Private privateWidth As Integer
Public Property Width() As Integer
Get
Return privateWidth
End Get
Set(ByVal value As Integer)
privateWidth = value
End Set
End Property
Private privateHeight As Integer
Public Property Height() As Integer
Get
Return privateHeight
End Get
Set(ByVal value As Integer)
privateHeight = value
End Set
End Property
Private privatePageSize As OfficeComponent.HtmlToPdf.PageSize
Public Property PageSize() As OfficeComponent.HtmlToPdf.PageSize
Get
Return privatePageSize
End Get
Set(ByVal value As OfficeComponent.HtmlToPdf.PageSize)
privatePageSize = value
End Set
End Property
Private privatePortrait As Boolean
Public Property Portrait() As Boolean
Get
Return privatePortrait
End Get
Set(ByVal value As Boolean)
privatePortrait = value
End Set
End Property
Private privateMargin As OfficeComponent.HtmlToPdf.PageMargins
Public Property Margin() As OfficeComponent.HtmlToPdf.PageMargins
Get
Return privateMargin
End Get
Set(ByVal value As OfficeComponent.HtmlToPdf.PageMargins)
privateMargin = value
End Set
End Property
Private privateConversionDelay As Integer
Public Property ConversionDelay() As Integer
Get
Return privateConversionDelay
End Get
Set(ByVal value As Integer)
privateConversionDelay = value
End Set
End Property
Private privateTimeout As Integer
Public Property Timeout() As Integer
Get
Return privateTimeout
End Get
Set(ByVal value As Integer)
privateTimeout = value
End Set
End Property
Private privateSinglePage As Boolean
Public Property SinglePage() As Boolean
Get
Return privateSinglePage
End Get
Set(ByVal value As Boolean)
privateSinglePage = value
End Set
End Property
Public Progress As EventHandler(Of ConverterProgressEventArgs)
#If WEB Then
Public Sub New()
MyBase.New(Nothing,Nothing)
End Sub
#End If
Public Sub New(ByVal commonDataPath As String, ByVal outputDir As String)
MyBase.New(commonDataPath, outputDir)
End Sub
Public Sub New(ByVal commonDataPath As String, ByVal outputDir As String, ByVal xmlFile As String)
MyBase.New(commonDataPath, outputDir, xmlFile)
End Sub
Private onComplete As Action(Of String)
Private onError As Action(Of Exception)
Private outputPath As String
Public Sub ExecuteAsync(ByVal onComplete As Action(Of String), ByVal onError As Action(Of Exception))
If Width <= 0 OrElse Height <= 0 Then
ShowError("Invalid Width or Height")
onComplete(Nothing)
Return
End If
If ConversionDelay < 0 Then
ShowError("Invalid conversion delay")
onComplete(Nothing)
Return
End If
' Set output path.
outputPath = Path.Combine(OutputDir, Me.GetType().Name & ".pdf")
If File.Exists(outputPath) Then
File.Delete(outputPath)
End If
' Create a new converter.
Dim c = New HtmlToPdfConverter() With {.ViewportWidth = Width, .ViewportHeight = Height, .PageSize = PageSize, .PageMargin = Margin, .Portrait = Portrait, .Delay = ConversionDelay, .Timeout = Timeout, .SinglePage = SinglePage}
If Progress IsNot Nothing Then
AddHandler c.Progress, Progress
End If
Me.onComplete = onComplete
Me.onError = onError
If ConvertUrl Then
If String.IsNullOrWhiteSpace(Url) Then
ShowError("Please specify the URL to convert.")
onComplete(Nothing)
Return
End If
' Convert URL
c.ConvertAsync(Url, outputPath, AddressOf OnConversionComplete)
Else
If String.IsNullOrWhiteSpace(HtmlString) Then
ShowError("Please specify the HTML string to convert.")
onComplete(Nothing)
Return
End If
' Convert the specified HTML string.
c.ConvertStringAsync(HtmlString, HtmlStringBaseUrl, outputPath, AddressOf OnConversionComplete)
End If
End Sub
Private Sub OnConversionComplete(ByVal sender As Object, ByVal e As AsyncCompletedEventArgs)
If e.Error IsNot Nothing Then
onError(e.Error)
Else
onComplete(outputPath)
End If
End Sub
Public Overrides Function Execute() As String
If Width <= 0 OrElse Height < 0 Then
ShowError("Invalid Width or Height")
Return Nothing
End If
If ConversionDelay < 0 Then
ShowError("Invalid conversion delay")
Return Nothing
End If
' Set output path.
Dim outputPath = Path.Combine(OutputDir, Me.GetType().Name & ".pdf")
If File.Exists(outputPath) Then
File.Delete(outputPath)
End If
' Create a new converter.
Dim c = New HtmlToPdfConverter() With {.ViewportWidth = Width, .ViewportHeight = Height, .PageSize = PageSize, .PageMargin = Margin, .Portrait = Portrait, .Delay = ConversionDelay, .Timeout = Timeout, .SinglePage = SinglePage}
If Progress IsNot Nothing Then
AddHandler c.Progress, Progress
End If
Try
If ConvertUrl Then
If String.IsNullOrWhiteSpace(Url) Then
ShowError("Please specify the URL to convert.")
Return Nothing
End If
' Convert URL
c.Convert(Url, outputPath)
Else
If String.IsNullOrWhiteSpace(HtmlString) Then
ShowError("Please specify the HTML string to convert.")
Return Nothing
End If
' Convert the specified HTML string.
c.ConvertString(HtmlString, HtmlStringBaseUrl, outputPath)
End If
Catch ex As Exception
ShowError(ex.Message)
End Try
Return outputPath
End Function
End Class
End Namespace