|
|
ExpertPDF PDF Creator for .NET
|
|
Developer's Guide
|
|
|
|
|
Table of Contents
|
|
|
|
|
1. Introduction
|
|
The ExpertPDF PDF Creator for .NET consists in a .NET assembly epdfcreator.dll
that can be referenced directly in any .NET application (ASP.NET, Windows Forms,
Console, Web Services, Windows Services, etc) to create PDF documents from the scratch
or modify existing PDF documents. The second dll needed by our component, epengine.dll will be automatically copied to your bin folder.
The component also offers a very powerful integrated HTML
to PDF converter which fully supports HTML tags and CSS styles and an integrated
RTF to PDF converter. Using the built-in converters you can easily create complex
PDF documents from your HTML and RTF documents that you can further customize by
adding texts, images, security features and interactive elements like bookmarks,
links, attachments or text notes.
The product does not require any installation and it does not use any printer driver
to perform conversion from HTML and RTF to PDF. It's just an assembly that you can
directly link with your .NET application and is using only Microsoft technologies
and tools.
The programming interface is object oriented, has a clear design, is extremely
easy to understand and use.
|
|
2. Installation
|
|
The ExpertPDF PDF Creator for .NET is delivered as a zip archive and it doesn't
have an installer. You have to simply unzip the archive in a folder on the disk.
Below is a brief description of the folders from the archive.
2.1 Bin Folder
The Bin folder contains the .NET assembly that you can reference in your
application and a XML file containing API documentation used by Microsoft Visual
Studio 2005 IntelliSense to offer inline documentation for classes, methods and
properties while writing code. The same documentation is available offline as a
.chm document in the Doc folder.
Bin/.NET_4.0 folder contains the .NET 4.0 assemblies you can use in your application and one prebuilt Windows Forms sample application that you can use to quickly check if the converter can run correctly in your environment.
epdfcreator.dll - is the PDF Creator library that you can link in any
.NET application, either Windows Forms or ASP.NET.
epdfcreator.xml - is the PDF Creator API documentation used by Microsoft
Visual Studio 2005 IntelliSense.
2.1 Doc Folder
Doc folder contains the PDF Creator the API reference in chm and html format
and this User's Guide document.
ExpertPdfCreatorAPI.chm - contains the PDF Creator API reference, with comments
for each class, method or property
HTML folder - contains the PDF Creator API reference in html format
Manual.html - is the document you are currently reading
2.3 Samples Folder
Samples folder contains C# full sample applications to offer you ready
to use code for ASP.NET and Windows Forms applications. The applications were created
with Microsoft Visual Studio. Each sample has a solution file sln that you
can directly open in Visual Studio.
There is a sample application for each of the most important features of the PDF
creator. In the WindowsForms folder there are Windows Forms applications
and in the AspNet folder there are web applications. You can find samples
for HTML to PDF conversion, RTF to PDF conversion, for adding images, fonts and
texts to the PDF document, for adding security features, bookmarks, headers and
footers, for modifying existing PDF documents.
|
|
|
3. Requirements and Recommendations
|
|
The recommended hardware and software resources for successfully using the ExpertPDF
PDF Creator for .NET are listed below. These requirements should be enough for any
of the PDF Creator features. We successfully tested the product in such an environment.
If during the usage of product you find any additional requirement for any of the
PDF Creator features please let us know about it.
|
|
Operating System: All Windows Versions
Hardware Architecture: 32-bit, 64-bit
Free RAM: 1GB
Microsoft .NET Framework 2.0, 3.5, 4.0, 4.5
Full trust level when used in ASP.NET applications
|
|
4. PDF Creator API
|
|
The converter API is fully documented in the Doc/ExpertPdfCreatorAPI.chm .
In order to use the PDF Creator library you have include the ExpertPdf.PdfCreator
namespace in your application.
|
|
4.1 Coordinates System and Graphic Units
|
|
|
The PDF Creator uses the point ( 1/72 inch ) as a graphic unit. All the coordinates
and sizes are expected to be specified in points. Sometimes, when the size of an
element (e.g. image) is known in pixels it is useful to convert pixels in points.
The PDF Creator API offers the UnitsConverter class to convert pixels in
points and points in pixels. Here are the prototypes of these static functions from
the UnitsConverter class:
|
public static float PointsToPixels(float points)
public static float PixelsToPoints(float pixels)
|
The coordinates system origin is located in the top left corner. The positive X
coordinates go to right and the positive Y coordinates go down like in the .NET
Windows Forms graphics.
|
|
4.2 Document Class
|
|
|
This class represents a PDF document in PDF Creator framework. A Document object
can be created from an existing PDF document or an empty document can be created
using the default constructor of the Document class. When creating a Document object
from an existing PDF document, the existing PDF document is passed to the Document
class constructor as the path of the .pdf file on disk or as a stream containing
the PDF document image. In either case the resulted Document object can be further
modified using the PDF Creator API. There are also Document constructors
accepting a password when creating a Document object form a password protected
PDF document. Here are the Document class constructors:
public Document()
public Document(Stream pdfStream)
public Document(string pdfFileName)
public Document(Stream pdfStream, string pdfPassword)
public Document(string pdfFileName, string pdfPassword)
The Document class offers access to the PDF pages collection, PDF fonts
collection, bookmarks, security features, templates and viewer preferences. For
example you can add a new page to the document pages collection using the
AddPage() method, adding a new font to the fonts collection using the AddFont()
methodor adding a new template using the AddTemplate() method. Below is
a sample C# code to show a typical usage scenario of the PDF Creator API to instantiate
a Document object and set various properties of the Document object. The code is
taken from the HTML to PDF converter sample and it creates a Document object, adds
a PDF page to the document and then adds a HTML to PDF converter element to the
page. Finally the page is sent as response to the client browser.
|
protected void btnConvert_Click(object sender, EventArgs e)
{
//create a PDF document
Document document = new Document();
//optional settings for the PDF document like margins,compression
level,
//security options, viewer preferences, document
information, etc
document.CompressionLevel = CompressionLevel.NormalCompression;
document.Margins = new Margins(10, 10, 0, 0);
document.Security.CanPrint = true;
document.Security.UserPassword = "";
document.DocumentInformation.Author = "HTML to PDF Converter";
document.ViewerPreferences.HideToolbar =
false;
//Add a first page to the document.
PdfPage page = document.Pages.AddNewPage(PageSize.A4,
new Margins(10, 10, 0, 0),
PageOrientation.Portrait);
// add a font to the document that can be
used for the text elements
PdfFont font = document.Fonts.Add(new System.Drawing.Font(
new System.Drawing.FontFamily("Times New Roman"), 10,
System.Drawing.GraphicsUnit.Point));
// convert HTML to PDF
HtmlToPdfElement htmlToPdfElement = new HtmlToPdfElement(xLocation, yLocation,
width, height, urlToConvert);
//optional settings for the HTML to PDF converter
htmlToPdfElement.FitWidth = cbFitWidth.Checked;
htmlToPdfElement.EmbedFonts = cbEmbedFonts.Checked;
htmlToPdfElement.LiveUrlsEnabled = cbLiveLinks.Checked;
htmlToPdfElement.RightToLeftEnabled = cbRTL.Checked;
htmlToPdfElement.ScriptsEnabled = cbClientScripts.Checked;
htmlToPdfElement.ActiveXEnabled = cbActiveXEnabled.Checked;
// add the HTML to PDF converter element to page
addResult = page.AddElement(htmlToPdfElement);
// send the generated PDF document to client
browser
document.Save(Response, false, "HtmlConvert.pdf");
}
|
|
4.2.1 Select PDF Standard (PDF/A, PDF/X,
PDF/SiqQ)
|
|
By default the PDF Creator can generate PDF documents in conformance with PDF 1.4
standard. This standard is accepted by Adobe Reader 5.0 and the later versions of
the Adobe Reader.
Using the Document class constructor with a parameter of PdfStandardSubset
type, the library can be instructed to generate PDF documents in conformance with
PDF/A, PDF/X and PDF/SiqQ and standards. These standards impose additional restrictions
to the generate document.
The PDF/A-1b standard (ISO 19005-1), used for long-term archiving of PDF documents,
requires that all the true type fonts used by the document to be embedded in the
document, the http links are disabled, the document does not use transparent objects,
the document information properties are disabled.
PDF/X-1a:2003 standard (ISO 15930-4), used to facilitate graphics exchange, requires
that all the true type fonts used by the document to be embedded in the document,
the http links are disabled, all the graphics are in CMYK color space, the document
does not use transparent objects.
PDF/SiqQ is a standard used by Adobe to ensure that a digitally signed document
does not contain items that could alter its appearance when viewed in different
environments. A PDF/SiqQ compliant document requires that all the true type fonts
used by the document to be embedded in the document and the http links to be disabled.
|
|
4.2.2 Select Color Space (RGB, CMYK, Grayscale)
|
|
By default the converter uses the RGB color space to draw graphics and images. Using
the Document class constructor with a parameter of ColorSpace type,
it is possible to instruct the converter to use the CMYK or Grayscale color space
when the PDF document is rendered.
|
|
4.3 PDF Renderers
|
|
A PDF renderer is an object capable of rendering PDF elements into the
final PDF document. Currently the PDF Creator API defines two types of renderers
derived from the ElementsRenderer abstract class: the PdfPage class which
renders elements in a PDF page and the Template class which renders the
elements in a template area repeated on each page of the PDF document. Both renderers
are capable to render the same graphic elements types like HTML to PDF converter
elements, shape elements texts and images but additionally the PdfPage renderer
can render other interactive elements like PDF links, digital signature elements,
attachments, text notes that cannot be rendered by a Template renderer.
|
4.3.1 PdfPage Class
|
|
The PdfPage class represents a page in the PDF document. A PdfPage class
object can be instantiated using the Document.AddPage() interface. When
calling the AddPage() method without parameters a page with the default
margins, size and orientation is created. The margins are inherited from the Document.Margins
property. The default orientation is portrait when adding the first page to the
document or the previous page orientation is inherited if there was a previous page
in document. The default size is A4 when adding the first page or the previous page
size if there was a previous page in document. However, any of these properties
can be specified to other overloadings of the AddPage() method.
|
4.3.2 Template Class
|
|
The Template class represents a content which is repeated on each page
of the PDF document. The templates can be used to create headers and footers, watermarks
or any other content that needs to be repeated on each page of the PDF document.
A Template can render all the graphic elements (e.g HTML to PDF converter, texts,
images, shapes) a PdfPage can render but it cannot render interactive elements like
PDF links, attachments, text notes. A Template class object can be instantiated
using the Document.AddTemplate() interface.
There two logical types of templates in PDF Creator: predefined templates like header
and footer and custom templates. Both predefined and custom are instances of the
Template class but the predefined templates dimensions are for example considered
when calculating the available client area in a PDF page.
|
4.3.2.1 Predefined Templates
|
|
The predefined templates are the document header, footer, left bar template and
right bar template. The predefined templates are automatically docked to the corresponding
side of the PDF page.
For example the predefined header is automatically docked to the top of the PDF
page which means the header location is the top left corner and the width of the
header template is the width of the page. Also if a predefined header was set, the
available client area in PDF page will start right under the header. Similar, if
a predefined footer was set, it will be docked to the bottom of page and the available
client area in PDF will end right above the footer template. It is recommended
to set the predefined templates before starting to add elements to the document.
Below is a sample to code to add a footer to the PDF document. Another special element
in the sample code below is the text element used to add page numbering. When adding
a text element to a template, the &p; token will be replaced with the current
page number and the &P token will be replaced with the total number of pages
of the PDF document. This is possible because the templates are rendered after the
PDF document main layer was rendered.
private void AddHtmlFooter(Document document, PdfFont footerPageNumberFont)
{
string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri;
string headerAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HeaderAndFooterHtml.htm";
//create a template to be added in the header and footer
document.FooterTemplate = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 60);
// create a HTML to PDF converter element to be added
to the header template
HtmlToPdfElement footerHtmlToPdf = new HtmlToPdfElement(headerAndFooterHtmlUrl);
document.FooterTemplate.AddElement(footerHtmlToPdf);
// add page number to the footer
TextElement pageNumberText = new TextElement(document.FooterTemplate.ClientRectangle.Width - 100, 30,
"This is page &p; of &P;
pages", footerPageNumberFont);
document.FooterTemplate.AddElement(pageNumberText);
}
|
4.3.2.2 Custom Templates
|
|
The custom templates can be used to add watermarks or any other content that must
be repeated in the same position on each page. In the code sample below, taken from
the ModifyExistingPdf sample, a watermark containing a text and an image is added
to an existing document:
protected void btnCreatePDF_Click(object sender, EventArgs e)
{
string pdfToModify = textBoxPdfFilePath.Text.Trim();
// create a PDF document
Document document = new Document(pdfToModify);
// get the first page the PDF document
PdfPage firstPage = document.Pages[0];
string logoImagePath = System.IO.Path.Combine(Server.MapPath("~"), @"img\logo.jpg");
// display image in the available space in
page and with a auto determined height to keep the aspect ratio
ImageElement imageElement1 = new ImageElement(0, 0, logoImagePath);
AddElementResult addResult = firstPage.AddElement(imageElement1);
// add image border
// add a border to watermark
RectangleElement imageBorderRectangleElement =
new RectangleElement(1, 1, addResult.EndPageBounds.Width,
addResult.EndPageBounds.Height);
firstPage.AddElement(imageBorderRectangleElement);
System.Drawing.Image logoImg = System.Drawing.Image.FromFile(logoImagePath);
// calculate the watermark location
System.Drawing.SizeF imageSizePx = logoImg.PhysicalDimension;
// transform from pixels to points
float imageWidthPoints = UnitsConverter.PixelsToPoints(imageSizePx.Width);
float imageHeightPoints = UnitsConverter.PixelsToPoints(imageSizePx.Height);
float watermarkXLocation = (firstPage.ClientRectangle.Width - imageWidthPoints)/2;
float watermarkYLocation = firstPage.ClientRectangle.Height / 4;
// add a template watermark to the document repeated
on each document page
// the watermark size is equal to image size
in points
Template watermarkTemplate = document.AddTemplate(new System.Drawing.RectangleF(watermarkXLocation, watermarkYLocation,
imageWidthPoints, imageHeightPoints + 20));
// add a standard font to the document
PdfFont watermarkTextFont = document.AddFont(StdFontBaseFamily.HelveticaBold);
watermarkTextFont.Size = 10;
// Add a text element to the watermark. You
can add any other graphic element to a template
TextElement watermarkTextElement = new TextElement(3, 0, "This is Watermark Text", watermarkTextFont);
watermarkTextElement.ForeColor = System.Drawing.Color.Red;
watermarkTextElement.Transparency = 100;
watermarkTemplate.AddElement(watermarkTextElement);
// add an image to the watermak
ImageElement watermarkImageElement = new ImageElement(0, 20, logoImg);
watermarkImageElement.Transparency = 100;
watermarkTemplate.AddElement(watermarkImageElement);
// add a border to watermark
RectangleElement watermarkRectangleElement =
new RectangleElement(0, 0, watermarkTemplate.ClientRectangle.Width,
watermarkTemplate.ClientRectangle.Height);
watermarkTemplate.AddElement(watermarkRectangleElement);
// dispose the image
logoImg.Dispose();
// save the document on http response stream
document.Save(Response, false, "ImagesDemo.pdf");
}
|
|
4.4 PDF Page Elements
|
|
A PDF page element represents anything that can be added to a renderer and it implements
the PageElement abstract class. The PDF Creator defines two types of page
elements: graphic elements that are inheriting the PageGraphicElement class
and interactive page elements inheriting directly the PageElement class.
The graphic elements have common properties like fore color, back color, transparency,
rotation angle. Examples of graphic elements are HTML to PDF Converter element,
RTF to PDF Converter element, text element, image element, shapes elements. Examples
of interactive page elements are internal link element, url link element, text note
element, file attachment element.
|
4.4.1 Page Graphic Elements
|
|
The page graphic elements inherit the PageGraphicElement class. This class
defines the following properties and methods that can be used to change the aspect
of the element:
ForeColor - this properties defines the color used to draw a shape for
example the color of a line when drawing a line element or the text color when drawing
a text
BackColor - this property defines the background color of a graphic element,
for example the background color of rectangle when rendering a rectangle element
Gradient - this property defines a gradient color to be used when filling
a shape like a rectangle element
Rotate(rotateAngle) - this method is used
to rotate clockwise the coordinates system with a specified angle before rendering
the graphic element.
Transparency - this property is used to set the graphic element transparency.
It is expected a value between 0 and 100 for the transparency. 0 means completely
transparent and 100 means completely opaque.
LineStyle - property is used to set the line width, dash style, line join
style, line cap style for the graphic elements rendering lines like rectangle element,
ellipse element, line element.
In the next sections each of the graphic elements will be described in detail.
|
4.4.1.1 HTML to PDF Converter Element
|
The integrated HTML to PDF Converter is implemented by the HtmlToPdfElement
graphic element. It basically includes the functionality of the HTML to PDF Converter
product and additionally offers the possibility to specify the position and the
size of the PDF content rendered from HTML and the possibility to add many HTML
to PDF conversions to same document.
A very useful feature is the possibility to know the size of the rendered content
in each page when the rendered content spans on many pages. The information about
the last rendered page can be taken from the AddElementResult object returned
after adding the element to a renderer like a page or template. Moreover, right
before rendering a the content on a PDF page a BeforeRenderNextPageEvent
even is raised and the BeforeRenderNextPageEventArgs object passed as a
parameter to the event handler offers details about the rendered size in the current
page and the possibility to stop element rendering by setting on true the Cancel
property of the BeforeRenderNextPageEventArgs object.
The HTMLToPdfElement offer many constructors that basically calls the following
two constructors with more or less default values for converting a URL or a HTML
string to PDF:
public HtmlToPdfElement(float x, float y, float width, float height,
string urlToConvert, int htmlViewerWidth, int htmlViewerHeight)
public HtmlToPdfElement(float x, float y, float width, float height,
string htmlStringToConvert, string htmlStringBaseURL,
int htmlViewerWidth, int htmlViewerHeight)
The variours constructor parameters are explined below.
The first constructor creates a URL to PDF converter element at the specified x
and y coordinates with the specified width and height.
The virtual browser width and height in pixels are specified by the htmlViewerWidth
and htmlViewerHeight parameters.
x - The x position in points where the rendered content will be placed
y- The y position in points where the rendered content will be placed
width - The destination width in points for the rendered content. If the
specified with is negative, the destination width will be given by the available
width in page or template
height - The destination height in points for the rendered content. If
the specified height is negative, the destination height will be auto determined
so all the content can be rendered. Please note that the specified height is the
effective height that will be rendered in the PDF document and does not include
for example the empty spaces introduced by custom or automatic page breaks.
urlToConvert - The URL to convert to PDF
htmlViewerWidth - The virtual browser width in pixels. The default value
is 1024 pixels. The effect of this parameter is similar with viewing the HTML page
in a browser window with the specified width. When this parameter is negative, the
converter will try to auto-determine the HTML page width from the HTML body element
width.
htmlViewerHeight - The virtual browser height in pixels. The default value
is 0 which means the height will be auto-determined. The effect of this parameter
is similar with viewing the HTML page in a browser window with the specified width
and height. When this paramter is negative, the converter will try to auto-determine
the HTML page height from the HTML body element height.
The second constructor creates a HTML string to PDF converter element at the specified
x and y coordinates with the specified width and height.
The virtual browser width and height in pixels is specified by the htmlViewerWidth
and htmlViewerHeight parameters.
htmlStringToConvert - The HTML string convert to PDF.
htmlStringBaseURL - The full URL of the page from where this string was
taken used to resolve the images and CSS files referenced by a relative URL in the
HTML string. This parameter is optional and the default value is NULL. When this
parameter is NULL no base URL will be used. This paramter has effect only if the
specified HTML string contains a HEAD element <base href="baseURL" />.
Below is a sample code extracted from the HtmlToPdf sample to demonstrate how easily
is to add HTML to PDF conversion to a PDF page and in the document header and footer
using the HtmlToPdfElement:
protected void btnConvert_Click(object sender, EventArgs e)
{
//create a PDF document
Document document = new Document();
//optional settings for the PDF document
like margins, compression level,
//security options, viewer preferences, document information,
etc
document.CompressionLevel = CompressionLevel.NormalCompression;
document.Margins = new Margins(10, 10, 0, 0);
document.Security.CanPrint = true;
document.Security.UserPassword = "";
document.DocumentInformation.Author = "HTML
to PDF Converter";
document.ViewerPreferences.HideToolbar = false;
//Add a first page to the document. The next pages will
inherit the settings from this page
PdfPage page = document.Pages.AddNewPage(PageSize.A4, new Margins(10,10,0, 0), PageOrientation.Portrait);
// the code below can be used to create a
page with default settings A4, document margins inherited, portrait orientation
//PdfPage page = document.Pages.AddNewPage();
// add a font to the document that can be used for the
texts elements
PdfFont font = document.Fonts.Add(new System.Drawing.Font(new System.Drawing.FontFamily("Times New Roman"), 10,
System.Drawing.GraphicsUnit.Point));
// add header and footer before renderng the content
if (cbAddHeader.Checked)
AddHtmlHeader(document);
if (cbAddFooter.Checked)
AddHtmlFooter(document, font);
// the result of adding an element to a PDF page
AddElementResult addResult;
// Get the specified location and size of
the rendered content
// A negative value for width and height means to auto
determine
// The auto determined width is the available
width in the PDF page
// and the auto determined height is the height necessary
to render all the content
float xLocation = float.Parse(textBoxXLocation.Text.Trim());
float yLocation = float.Parse(textBoxYLocation.Text.Trim());
float width = float.Parse(textBoxWidth.Text.Trim());
float height = float.Parse(textBoxHeight.Text.Trim());
if (radioConvertToSelectablePDF.Checked)
{
// convert HTML to PDF
HtmlToPdfElement htmlToPdfElement;
if (radioConvertURL.Checked)
{
// convert a URL to PDF
string urlToConvert = textBoxWebPageURL.Text.Trim();
htmlToPdfElement = new HtmlToPdfElement(xLocation, yLocation, width, height, urlToConvert);
}
else
{
// convert a HTML string to PDF
string htmlStringToConvert = textBoxHTMLCode.Text;
string baseURL = textBoxBaseURL.Text.Trim();
htmlToPdfElement = new HtmlToPdfElement(xLocation, yLocation, width, height, htmlStringToConvert, baseURL);
}
//optional settings for the HTML to PDF
converter
htmlToPdfElement.FitWidth = cbFitWidth.Checked;
htmlToPdfElement.EmbedFonts = cbEmbedFonts.Checked;
htmlToPdfElement.LiveUrlsEnabled = cbLiveLinks.Checked;
htmlToPdfElement.RightToLeftEnabled = cbRTL.Checked;
htmlToPdfElement.ScriptsEnabled = cbClientScripts.Checked;
htmlToPdfElement.ActiveXEnabled = cbActiveXEnabled.Checked;
// add theHTML to PDF converter element
to page
addResult = page.AddElement(htmlToPdfElement);
}
else
{
HtmlToImageElement htmlToImageElement;
// convert HTML to image and add image to PDF document
if (radioConvertURL.Checked)
{
// convert a URL to PDF
string urlToConvert = textBoxWebPageURL.Text.Trim();
htmlToImageElement = new HtmlToImageElement(xLocation, yLocation, width, height, urlToConvert);
}
else
{
// convert a HTML string to PDF
string htmlStringToConvert = textBoxHTMLCode.Text;
string baseURL = textBoxBaseURL.Text.Trim();
htmlToImageElement = new HtmlToImageElement(xLocation, yLocation, width, height, htmlStringToConvert, baseURL);
}
//optional settings for the HTML to PDF
converter
htmlToImageElement.FitWidth = cbFitWidth.Checked;
htmlToImageElement.ScriptsEnabled = cbClientScripts.Checked;
htmlToImageElement.ActiveXEnabled = cbActiveXEnabled.Checked;
addResult = page.AddElement(htmlToImageElement);
}
if (cbAdditionalContent.Checked)
{
// The code below can be used add some
other elements right under the conversion result
// like texts or another HTML to PDF conversion
// add a text element right under the HTML to PDF
document
PdfPage endPage = document.Pages[addResult.EndPageIndex];
TextElement nextTextElement = new TextElement(0, addResult.EndPageBounds.Bottom + 10, "Below there is another HTML to PDF Element", font);
nextTextElement.ForeColor = System.Drawing.Color.Green;
addResult = endPage.AddElement(nextTextElement);
// add another HTML to PDF converter element right
under the text element
endPage = document.Pages[addResult.EndPageIndex];
HtmlToPdfElement nextHtmlToPdfElement = new HtmlToPdfElement(0, addResult.EndPageBounds.Bottom + 10, "http://www.google.com");
addResult = endPage.AddElement(nextHtmlToPdfElement);
}
// send the generated PDF document to client browser
document.Save(Response, false, "HtmlConvert.pdf");
}
private void AddHtmlHeader(Document document)
{
string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri;
string headerAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HeaderAndFooterHtml.htm";
//create a template to be added in the header
and footer
document.HeaderTemplate = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 60);
// create a HTML to PDF converter element
to be added to the header template
HtmlToPdfElement headerHtmlToPdf = new HtmlToPdfElement(headerAndFooterHtmlUrl);
document.HeaderTemplate.AddElement(headerHtmlToPdf);
}
private void AddHtmlFooter(Document document, PdfFont footerPageNumberFont)
{
string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri;
string headerAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HeaderAndFooterHtml.htm";
//create a template to be added in the header
and footer
document.FooterTemplate = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 60);
// create a HTML to PDF converter element
to be added to the header template
HtmlToPdfElement footerHtmlToPdf = new HtmlToPdfElement(headerAndFooterHtmlUrl);
document.FooterTemplate.AddElement(footerHtmlToPdf);
// add page number to the footer
TextElement pageNumberText = new TextElement(document.FooterTemplate.ClientRectangle.Width - 100, 30,
"This is page &p;
of &P; pages", footerPageNumberFont);
document.FooterTemplate.AddElement(pageNumberText);
}
|
|
4.4.1.1.1 HTML to PDF Converter - Page
Breaks, Keep Together
|
|
The converter supports the following CSS styles to control the page breaks: page-break-before:always,
page-break-after:always and page-break-inside:avoid. For example, with the page-break-after:always
style applied to a HTML element (image, text, etc) you instruct the converter to
insert a page break right after that element is rendered.
By default the converter always tries to avoid breaking the text between PDF pages.
You can disable this behavior using the PdfConverter.AvoidTextBreak property. Also
you can enable the converter to avoid breaking the images between PDF pages using
the PdfConverter.AvoidImageBreak . By default this property is false.
An advanced and very useful feature when creating PDF reports is the Keep Together
feature which can be implemented with the page-break-inside:avoid style. This instructs
the converter to avoid breaking the content of a group of HTML elements you want
to keep together on the same page. If you think you can apply this style to a table,
a table row or a div element you can easily understand the utility of this feature.
Below is an example of using the page-break-inside:avoid style. The table contains
a large number of rows, each row containing an image in the left and a text in the
right and we don't want a row to span on two pages.
|
|
<table>
<tr style="page-break-inside : avoid">
<td>
<img width="100" height="100" src="img1.jpg">
</td>
<td>
My text 1
</td>
</tr>
<tr style="page-break-inside : avoid">
<td>
<img width="100" height="100" src="img2.jpg">
</td>
<td>
My text 2
</td>
</tr>
</table>
|
|
4.4.1.1.2 HTML to PDF Converter - Live
HTTP Links
|
|
The converter can convert any HTTP link from the HTML document into a link in the
PDF document. This works on links containing text, image or any other combination
supported by the HTML code. This is the default behavior of the converter. If you
don't want to get active links in the generated PDF document you can set HtmlToPdfElement.LiveUrlsEnabled = false.
|
|
4.4.1.1.3 HTML to PDF Converter -
Enable/Disable Client Scripts and ActiveX/Flash from HTML Page
|
|
The JavaScript code and ActiveX/Flash controls are disabled by default in the converted
page during conversion to a PDF. If you have JavaScript code that modifies the web
page on the client you can instruct the converter to execute that JavaScript code.
You can activate the JavaScript code . The properties from HtmlToPdfElement
class which allow you to activate the scripts and ActiveX/Flash when converting
to PDF file are:
|
|
public bool ScriptsEnabled { get; set; }
public bool ActiveXEnabled { get; set; }
|
|
4.4.1.1.4 HTML to PDF Converter -
Server Authentication
|
|
The converter offers support for any type of server authentication. For example
the converter can handle IIS authentication types like Integrated Windows
Authentication and Basic Authentication. The authentication is
disabled by default. To enable authentication you have to set the AuthenticationOptions
property of the HtmlToPdfElement object. Below you can find sample code
for setting the username and password for authentication when converting HTML to
PDF:
|
|
htmlToPdfElement.AuthenticationOptions.Username = username;
htmlToPdfElement.AuthenticationOptions.Password = password;
|
|
4.4.1.1.5 HTML to PDF Converter - Bookmarks
|
|
The converter can produce bookmarks in the generated PDF document for a list of
specified HTML tags. The bookmarking is controlled by the HtmlToPdfElement.PdfBookmarkOptions
property and is enabled only when a list of HTML tag names is specified by the
HtmlToPdfElement.PdfBookmarkOptions.TagNames property. For
example, to enable bookmarking of the H1 and H2 tags you can use the following line
of C# code:
|
|
htmlToPdfElement.PdfBookmarkOptions.TagNames =
new string[] { "H1", "H2" };
|
|
The tags to be bookmarked can be further filtered by CSS class name using the
HtmlToPdfElement.PdfBookmarkOptions.ClassNameFilter property.
For example, to filter only the H1 and H2 tags having the CSS class bookmark, the
following line of C# can be added to the previous one:
|
|
htmlToPdfElement.PdfBookmarkOptions.ClassNameFilter = "bookmark";
|
|
The ClassNameFilter property is case sensitive and the string value set for this
property must textually match the class attribute of the HTML tag to be bookmarked.
|
|
4.4.1.1.6 HTML to PDF Converter -
Internal Links in PDF
|
|
The converter automatically converts the HTML links with anchors found in the HTML
document to internal links in PDF. This features can be used to easily create table
of contents in the generated PDF document.
A HTML link with anchor consists in two HTML elements : a link defined with by a
<a href="#target">Internal Link</a> tag and
the target of the link defined by a <a name="target">Link
Target</a> tag. When the HTML to PDF converter finds this construction
it automatically generates an internal link in PDF from "Internal Link"
to "Link Target".
The generation of internal links can be disabled using the HtmlToPdfElement.InternalLinksEnabled
= false.
There are a few things to ensure in order to get the internal links correctly generated
in the PDF document. When converting an URL to PDF the URL must be fully qualified.
For example if a website MyWebsite has a default.aspx page with internal links which
is automatically served by the web server when the address http://MyWebsite is typed in the web browser address bar, then converting
directly the http://MyWebsite url might not produce
the correct internal links because the converter is unable to determine the web
page automatically served by the web server. Instead, when converting http://MyWebsite/default.aspx the internal links will always be correctly
generated. The HtmlToPdfElement has an optional internalLinksDocUrl
parameter in constructor which allows you to specify the fully qualified URL referenced
by the internal links before adding the HtmlToPdfElement to a PDF page.
When converting a HTML string to PDF it is recommended to always use the htmlStringBaseUrl
and internalLinksDocUrl parameters when the HtmlToPdfElement is constructed
in order to correctly get the internal links in the generated PDF document.
|
|
4.4.1.1.7 HTML to PDF Converter - JPEG Compression
of Images in PDF
|
|
The converter automatically compresses the images generated in PDF using the JPEG
compression algorithm to highly reduce the size of the generated PDF document. The
JPEG compression reduces the quality of the images. When the JPEG compression level
is increased the quality of the images in the PDF decreases.
The Document.JpegCompressionLevel property defines the current level used for JPEG
compression on a scale from 0 to 100. When the compression level is 0 the compression
is the worst and the image quality is the best. The default JPEG compression level
used by the converter is 10 which offers a good balance between the images quality
and the size of the generated PDF document.
If you want to obtain the best image quality it is possible to completely disable
the JPEG compression of the images by setting the Document.JpegCompressionEnabled
to false.
|
|
4.4.1.1.8 HTML to PDF Converter - Retrieve
HTML Elements Mapping to PDF
|
|
This is a very powerful feature of the converter which allows you to obtain the
position in the generated PDF document for any HTML element. Knowing the position
in the generated PDF document of any element from the HTML document allows you to
create bookmarks for elements from the HTML document, create internal links between
HTML elements, place texts or images over the HTML elements or assign a digital
signature to a certain element from HTML.
This feature can accessed using the HtmlToPdfElement.HtmlElementsMappingOptions
property. This property allows you defined a list with HTML IDs of the HTML elements
to for which you want to retrieve position using the HtmlElementIds property
or a list with the HTML tag names of the HTML elements for which you want to retrieve
position using the HtmlTagNames property.
The HtmlElementsMappingOptions property must be set before adding the HtmlToPdfElement
to a PDF page.
The HTML elements mapping is returned in the HtmlToPdfElement.HtmlElementsMappingOptions.HtmlElementsMappingResult.
The HtmlElementsMapping result is a collection of HtmlElementMapping objects which
offers the PDF page index where the element was mapped by the converter and the
rectangle where the element was rendered inside that page, the element HTML ID,
the element tag name, the element text and the element outer HTML code.
In the code sample below, all the H1 and IMG elements and the
elements with the ID MyID1 and MyID2 will be highlighted with
a red rectangle in the generated PDF:
// create the HtmlToPdfElement
htmlToPdfElement = new HtmlToPdfElement("http://www.html-to-pdf.net");
// define the list with the HTML tags of the elements for which you
want to retrieve position
htmlToPdfElement.HtmlElementsMappingOptions.HtmlTagNames = new string[] { "IMG", "H1" };
// define the list with the HTML IDs of the elements for which you
want to retrieve position
htmlToPdfElement.HtmlElementsMappingOptions.HtmlElementIds = new string[] { "MyID1", "MyID2" };
// add the element to a PDF page
page.AddElement(htmlToPdfElement);
// iterate over the HTML elements mappings and draw a red rectangle
around the element in PDF
foreach (HtmlElementMapping elementMapping in htmlToPdfElement.HtmlElementsMappingOptions.HtmlElementsMappingResult)
{
// iterate over the positions of the HTML element in PDF because a
HTML element
// can span on many PDF pages
foreach (HtmlElementPdfRectangle pdfRectangle in elementMapping.PdfRectangles)
{
// get the PDF page where the HTML element was rendered
PdfPage elementPdfPage = document.Pages[pdfRectangle.PageIndex];
RectangleF elementPdfRectangle = pdfRectangle.Rectangle;
// get the rectangle inside the PDF page where the element was rendered
RectangleElement elementHighlightRectangle = new RectangleElement(elementPdfRectangle.X, elementPdfRectangle.Y,
elementPdfRectangle.Width, elementPdfRectangle.Height);
elementHighlightRectangle.ForeColor = Color.Red;
elementPdfPage.AddElement(elementHighlightRectangle);
}
}
|
|
4.4.1.2 HTML to Image Converter Element |
The integrated HTML to Image Converter is implemented by the HtmlToImageElement
graphic element. It basically includes the functionality of the HTML to PDF Converter
product when converting to a PDF with embedded image and additionally offers the
possibility to specify the position and the size of the rendered image and the possibility
to add many HTML to Image conversions to same document.
A very useful feature is the possibility to know the size of the rendered content
in each page when the rendered content spans on many pages. The information about
the last rendered page can be taken from the AddElementResult object returned
after adding the element to a renderer like a page or template. Moreover, right
before rendering a the content on a PDF page a BeforeRenderNextPageEvent
even is raised and the BeforeRenderNextPageEventArgs object passed as a
parameter to the event handler offers details about the rendered size in the current
page and the possibility to stop element rendering by setting on true the Cancel
property of the BeforeRenderNextPageEventArgs object.
The HtmlToImageElement offer many constructors that basically calls the
following two constructors with more or less default values for converting a URL
or a HTML string to image:
public HtmlToImageElement(float x, float y, float width, float height,
string urlToConvert, int htmlViewerWidth, int htmlViewerHeight)
public HtmlToImageElement(float x, float y, float width, float height,
string htmlStringToConvert, string htmlStringBaseURL,
int htmlViewerWidth, int htmlViewerHeight)
The various constructor parameters are explained below.
The first constructor creates a URL to Image converter element at the specified
x and y coordinates with the specified width and height.
The virtual browser width and height in pixels are specified by the htmlViewerWidth
and htmlViewerHeight parameters.
x - The x position in points where the rendered content will be placed
y- The y position in points where the rendered content will be placed
width - The destination width in points for the rendered content. If the
specified with is negative, the destination width will be given by the available
width in page or template
height - The destination height in points for the rendered content. If
the specified height is negative, the destination height will be auto determined
so all the content can be rendered. Please note that the specified height is the
effective height that will be rendered in the PDF document and does not include
for example the empty spaces introduced by custom or automatic page breaks.
urlToConvert - The URL to convert to PDF
htmlViewerWidth - The virtual browser width in pixels. The default value
is 1024 pixels. The effect of this parameter is similar with viewing the HTML page
in a browser window with the specified width. When this parameter is negative, the
converter will try to auto-determine the HTML page width from the HTML body element
width.
htmlViewerHeight - The virtual browser height in pixels. The default value
is 0 which means the height will be auto-determined. The effect of this parameter
is similar with viewing the HTML page in a browser window with the specified width
and height. When this paramter is negative, the converter will try to auto-determine
the HTML page height from the HTML body element height.
The second constructor creates a HTML string to Image converter element at the specified
x and y coordinates with the specified width and height.
The virtual browser width and height in pixels is specified by the htmlViewerWidth
and htmlViewerHeight parameters.
htmlStringToConvert - The HTML string convert to PDF.
htmlStringBaseURL - The full URL of the page from where this string was
taken used to resolve the images and CSS files referenced by a relative URL in the
HTML string. This parameter is optional and the default value is NULL. When this
parameter is NULL no base URL will be used. This paramter has effect only if the
specified HTML string contains a HEAD element <base href="baseURL" />.
The sample code for the HtmlToPdfElement also contains sample code for the HtmlToImageElement.
|
|
4.4.1.3 RTF to PDF Converter Element
|
The integrated RTF to PDF Converter is implemented by the RtfToPdfElement
graphic element. It basically includes the functionality of the RTF to PDF Converter
product and additionally offers the possibility to specify the position and the
size of the rendered content and the possibility to add many RTF to PDF conversions
to same document.
A very useful feature is the possibility to know the size of the rendered content
in each page when the rendered content spans on many pages. The information about
the last rendered page can be taken from the AddElementResult object returned
after adding the element to a renderer like a page or template. Moreover, right
before rendering a the content on a PDF page a BeforeRenderNextPageEvent
even is raised and the BeforeRenderNextPageEventArgs object passed as a
parameter to the event handler offers details about the rendered size in the current
page and the possibility to stop element rendering by setting on true the Cancel
property of the BeforeRenderNextPageEventArgs object.
The RtfToPdfElement offers many constructors that basically calls the following
constructor with more or less default values
public RtfToPdfElement(float x, float y, float width, float height,
string rtfStringToConvert, int rtfViewerWidth, int rtfViewerHeight)
The constructor creates a RTF to PDF Converter element at the specified x
and y coordinates with the specified width and height.
The virtual viewer width and height in pixels are specified by the rtfViewerWidth
and rtfViewerHeight parameters.
x - The x position in points where the rendered content will be placed
y- The y position in points where the rendered content will be placed
width - The destination width in points for the rendered content. If the
specified with is negative, the destination width will be given by the available
width in page or template
height - The destination height in points for the rendered content. If
the specified height is negative, the destination height will be auto determined
so all the content can be rendered. Please note that the specified height is the
effective height that will be rendered in the PDF document and does not include
for example the empty spaces introduced by custom or automatic page breaks.
rtfStringToConvert - The RTF string to convert to PDF
rtfViewerWidth - The RTF viewer width in pixels. The default value is 800
pixels. The effect of this parameter is similar with viewing the RTF viewer window
with the specified width. When this parameter is negative, the converter will try
to auto-determine the RTF document width.
rtfViewerHeight - The RTF viewerheight in pixels. The default value is
0 which means the height will be auto-determined. The effect of this parameter is
similar with viewing the RTF document in a viewer window with the specified width
and height. When this parameter is negative, the converter will try to auto-determine
the RTF document height.
Below is a sample code extracted from the RtfToPdfDemo sample application:
protected void btnCreatePDF_Click(object sender, EventArgs e)
{
//create a PDF document
Document document = new Document();
//optional settings for the PDF document
like margins, compression level,
//security options, viewer preferences, document information,
etc
document.CompressionLevel = CompressionLevel.NormalCompression;
document.Margins = new Margins(10, 10, 0, 0);
document.Security.CanPrint = true;
document.Security.UserPassword = "";
document.DocumentInformation.Author = "RTF
to PDF Converter";
document.ViewerPreferences.HideToolbar = false;
//Add a first page to the document. The next pages will
inherit the settings from this page
PdfPage page = document.Pages.AddNewPage(PageSize.A4, new Margins(10, 10, 0, 0), PageOrientation.Portrait);
// the code below can be used to create a
page with default settings A4, document margins inherited, portrait orientation
//PdfPage page = document.Pages.AddNewPage();
// add a font to the document that can be used for the
texts elements
PdfFont font = document.Fonts.Add(new Font(new FontFamily("Times New Roman"), 10, GraphicsUnit.Point));
// add header and footer before renderng
the content
if (cbAddHeader.Checked)
AddHtmlHeader(document);
if (cbAddFooter.Checked)
AddHtmlFooter(document, font);
// the result of adding an element to a PDF
page
AddElementResult addResult;
// Get the specified location and size of the rendered
content
// A negative value for width and height
means to auto determine
// The auto determined width is the available width in
the PDF page
// and the auto determined height is the
height necessary to render all the content
float xLocation = float.Parse(textBoxXLocation.Text.Trim());
float yLocation = float.Parse(textBoxYLocation.Text.Trim());
float width = float.Parse(textBoxWidth.Text.Trim());
float height = float.Parse(textBoxHeight.Text.Trim());
// Create the RTF to PDF converter element
string rtfString = System.IO.File.ReadAllText(textBoxRtfFile.Text.Trim());
RtfToPdfElement rtfToPdfElement = new RtfToPdfElement(xLocation, yLocation, width, height, rtfString,
RtfToPdfElement.DEFAULT_RTF_VIEWER_WIDTH_PX, -1);
//optional settings for the RTF to PDF converter
rtfToPdfElement.FitWidth = cbFitWidth.Checked;
rtfToPdfElement.EmbedFonts = cbEmbedFonts.Checked;
// add theHTML to PDF converter element to
page
addResult = page.AddElement(rtfToPdfElement);
if (cbAdditionalContent.Checked)
{
// The code below can be used add some other elements
right under the conversion result
// like texts or another RTF to PDF conversion
// add a text element right under the
HTML to PDF document
PdfPage endPage = document.Pages[addResult.EndPageIndex];
TextElement nextTextElement = new TextElement(0, addResult.EndPageBounds.Bottom + 10, "Below you can add another RTF to PDF Element", font);
nextTextElement.ForeColor = Color.Green;
addResult = endPage.AddElement(nextTextElement);
}
// send the generated PDF document to client browser
document.Save(Response, false, "HtmlConvert.pdf");
}
private void AddHtmlHeader(Document document)
{
string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri;
string headerAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HeaderAndFooterHtml.htm";
//create a template to be added in the header
and footer
document.HeaderTemplate = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 60);
// create a HTML to PDF converter element
to be added to the header template
HtmlToPdfElement headerHtmlToPdf = new HtmlToPdfElement(headerAndFooterHtmlUrl);
document.HeaderTemplate.AddElement(headerHtmlToPdf);
}
private void AddHtmlFooter(Document document, PdfFont footerPageNumberFont)
{
string thisPageURL = HttpContext.Current.Request.Url.AbsoluteUri;
string headerAndFooterHtmlUrl = thisPageURL.Substring(0, thisPageURL.LastIndexOf('/')) + "/HeaderAndFooterHtml.htm";
//create a template to be added in the header
and footer
document.FooterTemplate = document.AddTemplate(document.Pages[0].ClientRectangle.Width, 60);
// create a HTML to PDF converter element
to be added to the header template
HtmlToPdfElement footerHtmlToPdf = new HtmlToPdfElement(headerAndFooterHtmlUrl);
document.FooterTemplate.AddElement(footerHtmlToPdf);
// add page number to the footer
TextElement pageNumberText = new TextElement(document.FooterTemplate.ClientRectangle.Width - 100, 30,
"This is page &p;
of &P; pages", footerPageNumberFont);
document.FooterTemplate.AddElement(pageNumberText);
}
|
|
4.4.1.4 Text Element And Fonts
|
The Text Element allows adding texts to a PDF document and is implemented by the
TextElement class. The TextElement offers many constructors that
basically calls the following constructor with more or less default values:
public TextElement(float x, float y, float width, float height,
string text, PdfFont font, PdfColor textColor)
The constructor creates a paginable text element that will be rendered in the specified
rectangle using the specified width, height, font and color.
If the text pagination is not allowed ( Paginate property of the TextElement
is false ), the text will be written on current page, the rendered text height being
given by the minimum between the specified height and the available height on page.
The remaining text and the text bounds inside the current page are returned in the
AddTextElementResult object when the element is added to a renderer.
If the text pagination is allowed ( Paginate property of the TextElement
is true ) and the text needs pagination (the specified height is bigger than the
available space on page), the height parameter will be ignored and the text will
be rendered to the end using the necessary height. The text bounds inside the last
page and the last page index are returned in the AddTextElementResult object when
the element is added to a renderer.
If the text pagination is allowed but the text does not need pagination (the specified
height is less than the available space on page), the rendered text will be truncated
to fit the specified height. The text bounds inside the current page and the last
page index are returned in the AddTextElementResult object when the element
is added to a renderer.
x - The start x coordinate where the text will be rendered
y- The start y coordinate where the text
width - The width of the destination rectangle
height - The height of the destination rectangle
text - The text to be rendered
font - The text font
textColor - The text color
Below is a sample code extracted from the TextsAndFontsDemo sample application:
protected void btnCreatePDF_Click(object sender, EventArgs e)
{
// create a PDF document
Document document = new Document();
// add a page to the PDF document
PdfPage firstPage = document.AddPage();
// Create a Times New Roman .NET font of 10 points
System.Drawing.Font ttfFont = new System.Drawing.Font("Times New Roman", 10, System.Drawing.GraphicsUnit.Point);
// Create a Times New Roman Italic .NET font of 10 points
System.Drawing.Font ttfFontItalic = new System.Drawing.Font("Times New Roman", 10,
System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point);
// Create a Times New Roman Bold .NET font
of 10 points
System.Drawing.Font ttfFontBold = new System.Drawing.Font("Times New Roman", 10,
System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point);
// Create a Times New Roman Bold .NET font of 10 points
System.Drawing.Font ttfFontBoldItalic =
new System.Drawing.Font("Times New Roman", 10,
System.Drawing.FontStyle.Bold | System.Drawing.FontStyle.Italic, System.Drawing.GraphicsUnit.Point);
// Create a Sim Sun .NET font of 10 points
System.Drawing.Font ttfCJKFont = new System.Drawing.Font("SimSun", 10,
System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point);
// Create the PDF fonts based on the .NET true type fonts
PdfFont newTimesFont = document.AddFont(ttfFont);
PdfFont newTimesFontItalic = document.AddFont(ttfFontItalic);
PdfFont newTimesFontBold = document.AddFont(ttfFontBold);
PdfFont newTimesFontBoldItalic = document.AddFont(ttfFontBoldItalic);
// Create the embedded PDF fonts based on the .NET true
type fonts
PdfFont newTimesEmbeddedFont = document.AddFont(ttfFont, true);
PdfFont newTimesItalicEmbeddedFont = document.AddFont(ttfFontItalic, true);
PdfFont newTimesBoldEmbeddedFont = document.AddFont(ttfFontBold,
true);
PdfFont newTimesBoldItalicEmbeddedFont = document.AddFont(ttfFontBoldItalic,
true);
PdfFont cjkEmbeddedFont = document.AddFont(ttfCJKFont,
true);
// Create a standard Times New Roman Type 1 Font
PdfFont stdTimesFont = document.AddFont(StdFontBaseFamily.TimesRoman);
PdfFont stdTimesFontItalic = document.AddFont(StdFontBaseFamily.TimesItalic);
PdfFont stdTimesFontBold = document.AddFont(StdFontBaseFamily.TimesBold);
PdfFont stdTimesFontBoldItalic = document.AddFont(StdFontBaseFamily.TimesBoldItalic);
// Create CJK standard Type 1 fonts
PdfFont cjkJapaneseStandardFont = document.AddFont(StandardCJKFont.HeiseiKakuGothicW5);
PdfFont cjkChineseTraditionalStandardFont = document.AddFont(StandardCJKFont.MonotypeHeiMedium);
// Add text elements to the document
TextElement trueTypeText = new TextElement(0, 10, "True Type Fonts Demo:", newTimesFontBold);
AddElementResult addResult = firstPage.AddElement(trueTypeText);
// Create the text element
TextElement textElement1 = new TextElement(20, addResult.EndPageBounds.Bottom + 10, "Hello World !!!!", newTimesFont);
// Add element to page. The result of adding
the text element is stored into the addResult object
// which can be used to get information about the rendered
size in PDF page.
addResult = firstPage.AddElement(textElement1);
// Add another element 5 points below the
text above. The bottom of the text above is taken from the AddElementResult object
// set the font size
newTimesFontItalic.Size = 15;
TextElement textElement2 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "Hello World !!!!", newTimesFontItalic);
textElement2.ForeColor = System.Drawing.Color.Green;
addResult = firstPage.AddElement(textElement2);
newTimesFontBoldItalic.Size = 20;
TextElement textElement3 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "Hello World !!!!", newTimesFontBoldItalic);
textElement3.ForeColor = System.Drawing.Color.Blue;
addResult = firstPage.AddElement(textElement3);
TextElement stdTypeText = new TextElement(0, addResult.EndPageBounds.Bottom + 10, "Standard PDF Fonts Demo:", newTimesFontBold);
addResult = firstPage.AddElement(stdTypeText);
TextElement textElement4 = new TextElement(20, addResult.EndPageBounds.Bottom + 10, "Hello World !!!!", stdTimesFont);
addResult = firstPage.AddElement(textElement4);
stdTimesFontItalic.Size = 15;
TextElement textElement5 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "Hello World !!!!", stdTimesFontItalic);
textElement5.ForeColor = System.Drawing.Color.Green;
addResult = firstPage.AddElement(textElement5);
stdTimesFontBoldItalic.Size = 20;
TextElement textElement6 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "Hello World !!!!", stdTimesFontBoldItalic);
textElement6.ForeColor = System.Drawing.Color.Blue;
addResult = firstPage.AddElement(textElement6);
// embedded true type fonts
TextElement embeddedTtfText = new TextElement(0, addResult.EndPageBounds.Bottom + 10, "Embedded True Type Fonts Demo:", newTimesFontBold);
addResult = firstPage.AddElement(embeddedTtfText);
// arabic right to left text
newTimesEmbeddedFont.Size = 15;
TextElement textElement7 = new TextElement(20, addResult.EndPageBounds.Bottom + 10, "مرحبا العالم!!!!", newTimesEmbeddedFont);
textElement7.RightToLeftLanguage = true;
addResult = firstPage.AddElement(textElement7);
// russian text
TextElement textElement8 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "Появление на свет!!", newTimesEmbeddedFont);
addResult = firstPage.AddElement(textElement8);
//japanesse text
TextElement textElementJapanese = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "こんにちは世界!", cjkEmbeddedFont);
addResult = firstPage.AddElement(textElementJapanese);
//chinese text
TextElement textElementChinese = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "你好世界! !", cjkEmbeddedFont);
addResult = firstPage.AddElement(textElementChinese);
TextElement stdCJKText = new TextElement(0, addResult.EndPageBounds.Bottom + 10, "Standard CJK Fonts Demo:", newTimesFontBold);
addResult = firstPage.AddElement(stdCJKText);
// Hello World in Japanese
TextElement textElement10 = new TextElement(20, addResult.EndPageBounds.Bottom + 20, "こんにちは世界!", cjkJapaneseStandardFont);
addResult = firstPage.AddElement(textElement10);
// Hello World in Chinese Traditional
TextElement textElement11 = new TextElement(20, addResult.EndPageBounds.Bottom + 5, "你好世界! !", cjkChineseTraditionalStandardFont);
addResult = firstPage.AddElement(textElement11);
// save the document to http response stream
document.Save(Response, false, "FontsAndTexts.pdf");
}
|
|
|
4.4.1.5 Image Element
|
The Image Element allows adding images to a PDF document and is implemented by the
ImageElement class. The ImageElement offers many constructors
that basically calls the following two constructors with more or less default values:
public ImageElement(float x, float y, float destWidth, float destHeight,
string filePath)
public ImageElement(float x, float y, float destWidth, float destHeight,
System.Drawing.Image imageObj)
The first constructor creates an ImageElement from the specified file that
will be rendered at the position (x,y) with the (destWidth,destHeight) size.
The second constructor creates an ImageElement from the specified System.Drawing.Image
object that will be rendered at the position (x,y) with the (destWidth,destHeight)
size.
x - The X location where this element will be rendered
y- The Y location where this element will be rendered
destWidth - The destination rectangle width
destHeight- The destination rectangle height
filePath - The image file path
imageObj - The System.Drawing.Image object
Below is a sample code extracted from the ImagesDemo sample application:
protected void btnCreatePDF_Click(object sender, EventArgs e)
{
// create a PDF document
Document document = new Document();
// add a page to the PDF document
PdfPage firstPage = document.AddPage();
string imagesPath = System.IO.Path.Combine(Server.MapPath("~"), "Images");
// display image in the available space in
page and with a auto determined height to keep the aspect ratio
ImageElement imageElement1 = new ImageElement(0, 0, System.IO.Path.Combine(imagesPath, "html-to-pdf-box-250.PNG"));
AddElementResult addResult = firstPage.AddElement(imageElement1);
// display image with the specified width
and the height auto determined to keep the aspect ratio
// the images is displayed to the right of the previous
image and the bounds of the image inside the current page
// are taken from the AddElementResult object
ImageElement imageElement2 = new ImageElement(addResult.EndPageBounds.Right + 10, 0, 100,
System.IO.Path.Combine(imagesPath,
"html-to-pdf-box-250.PNG"));
addResult = firstPage.AddElement(imageElement2);
// Display image with the specified width and the specified
height. It is possible for the image to not preserve the aspect ratio
// The images is displayed to the right of
the previous image and the bounds of the image inside the current page
// are taken from the AddElementResult object
ImageElement imageElement3 = new ImageElement(addResult.EndPageBounds.Right + 10, 0, 200, 100,
System.IO.Path.Combine(imagesPath, "html-to-pdf-box-250.PNG"));
addResult = firstPage.AddElement(imageElement3);
// save the document on http response stream
document.Save(Response, false, "ImagesDemo.pdf");
}
|
|
4.4.1.6 Shape Elements
|
The PDF Creator defines the following shape elements: LineElement, RectangleElement,
EllipseElement, EllipseArcElement, EllipseSliceElement, BezierCurveElement, PolygonElement.
Below is a sample code extracted from the ShapesDemo sample application:
protected void btnCreatePDF_Click(object sender, EventArgs e)
{
// create a PDF document
Document document = new Document();
// add a page to the PDF document
PdfPage firstPage = document.AddPage();
// draw rectangle
RectangleElement rectangle1 = new RectangleElement(10, 10, 150, 100);
rectangle1.ForeColor = System.Drawing.Color.Blue;
rectangle1.LineStyle.LineWidth = 5; // a 5 points line
width
rectangle1.LineStyle.LineJoinStyle = LineJoinStyle.RoundJoin;
firstPage.AddElement(rectangle1);
// draw colored rectangle
RectangleElement rectangle2 = new RectangleElement(200, 10, 150, 100);
rectangle2.ForeColor = System.Drawing.Color.Blue;
rectangle2.BackColor = System.Drawing.Color.Green;
firstPage.AddElement(rectangle2);
// draw gradient colored rectangle
RectangleElement rectangle3 = new RectangleElement(400, 25, 100, 50);
rectangle3.ForeColor = System.Drawing.Color.Blue;
rectangle3.Gradient = new GradientColor( GradientDirection.Vertical, System.Drawing.Color.Green, System.Drawing.Color.Blue);
firstPage.AddElement(rectangle3);
// draw ellipse
EllipseElement ellipse1 = new EllipseElement(75, 200, 70, 50);
ellipse1.ForeColor = System.Drawing.Color.Blue;
ellipse1.LineStyle.LineDashStyle = LineDashStyle.Dash;
firstPage.AddElement(ellipse1);
// draw ellipse
EllipseElement ellipse2 = new EllipseElement(275, 200, 70, 50);
ellipse2.ForeColor = System.Drawing.Color.Blue;
ellipse2.BackColor = System.Drawing.Color.Green;
firstPage.AddElement(ellipse2);
// draw ellipse
EllipseElement ellipse3 = new EllipseElement(450, 200, 50, 25);
ellipse3.ForeColor = System.Drawing.Color.Blue;
ellipse3.Gradient = new GradientColor(GradientDirection.Vertical, System.Drawing.Color.Green, System.Drawing.Color.Blue);
firstPage.AddElement(ellipse3);
BezierCurveElement bezierCurve1 = new BezierCurveElement(10, 350, 100, 300, 200, 400, 300, 350);
bezierCurve1.ForeColor = System.Drawing.Color.Blue;
bezierCurve1.LineStyle.LineWidth = 3;
bezierCurve1.LineStyle.LineJoinStyle = LineJoinStyle.RoundJoin;
firstPage.AddElement(bezierCurve1);
BezierCurveElement bezierCurve2 = new BezierCurveElement(10, 350, 100, 400, 200, 300, 300, 350);
bezierCurve2.ForeColor = System.Drawing.Color.Green;
bezierCurve2.LineStyle.LineWidth = 3;
bezierCurve2.LineStyle.LineJoinStyle = LineJoinStyle.RoundJoin;
firstPage.AddElement(bezierCurve2);
// save the document to http response stream
document.Save(Response, false, "Shapes.pdf");
}
|
|
4.4.2 Page Interactive Elements
|
|
The page interactive elements inherit directly from the PageElement class.
They add interactive features to the PDF document like internal and URL links, file
attachments and links, popup text notes, digital signatures, etc.
In the next sections each of the graphic elements will be described in detail.
|
|
4.4.2.1 Digital Signature Element
|
Digital signatures can be added to a PDF document using the DigitalSignatureElement.
Adding a digital signature requires a PKCS#12 certificate provided as a .pfx or
a .p12 file.
Below is a sample code extracted from the Security sample application:
protected void btnCreatePDF_Click(object sender, EventArgs e)
{
// create a PDF document
Document document = new Document();
// password protect the PDF document if necessary by
setting the user and owner passwords
// the user password is required to view
the document
// the owner password is required to modify the document
permissions
// An empty string means the document is
not password protected
document.Security.UserPassword = "";
document.Security.OwnerPassword = "";
document.Security.CanPrint = false;
document.Security.CanEditContent = true;
// add a page to the PDF document
PdfPage firstPage = document.AddPage();
string logoImagePath = System.IO.Path.Combine(Server.MapPath("~"), @"img\logo.jpg");
string certificateFilePath = System.IO.Path.Combine(Server.MapPath("~"), "oss.pfx");
// create the area where the digital signature
will be displayed in the PDF document
// in this sample the area is a logo image but it could
be anything else
ImageElement logoElement = new ImageElement(0, 0, logoImagePath);
AddElementResult addResult = firstPage.AddElement(logoElement);
//get the #PKCS 12 certificate from file
DigitalCertificatesCollection certificates = DigitalCertificatesStore.GetCertificates(certificateFilePath,
"osspswd");
DigitalCertificate certificate = certificates[0];
// create the digital signature over the logo image element
DigitalSignatureElement signature = new DigitalSignatureElement(addResult.EndPageBounds, certificate);
signature.Reason = "Protect the document from unwanted
changes";
signature.ContactInfo = "The contact email
is office@outsidesoftware.com";
signature.Location = "Development server";
firstPage.AddElement(signature);
// save the document on http response stream
document.Save(Response, false, "Security.pdf");
}
|
|
|
4.4.2.2 Other Interactive Page Elements
|
The PDF Creator also defines the following interactive elements that can be added
to a page: LinkUrlElement, InternalLinkElement, SoundLinkElement, FileLinkElement,
FileAttachmentElement, TextNoteElement that can be used to add interactive
features to the PDF document.
|
|
|
4.5 Bookmarks
|
|
The PDF Creator offers an API for adding bookmarks to a PDF document. Using the
AddBookmark() methods of the Document class you can add root or
child bookmarks. The code sample below is extracted from the BookmarksDemo
sample application:
protected void btnCreatePDF_Click(object sender, EventArgs e)
{
// create a PDF document
Document document = new Document();
// add a page to the PDF document
PdfPage firstPage = document.AddPage();
//add a root bookmark to the first page
Bookmark firstPageBookmark = document.AddBookmark("First
Page", new ExplicitDestination(firstPage));
string imagesPath = System.IO.Path.Combine(Server.MapPath("~"), "Images");
// display image in the available space in page and with
a auto determined height to keep the aspect ratio
ImageElement imageElement1 = new ImageElement(0, 0, System.IO.Path.Combine(imagesPath, "html-to-pdf-box-250.PNG"));
AddElementResult addResult = firstPage.AddElement(imageElement1);
// add a child bookmark to this image
document.AddBookmark("HTML to PDF Converter", new ExplicitDestination(firstPage, new System.Drawing.PointF(0,0)), firstPageBookmark);
// display image in the available space in
page and with a auto determined height to keep the aspect ratio
ImageElement imageElement2 = new ImageElement(0, 200, System.IO.Path.Combine(imagesPath, "rtftopdf-converter-250.jpg"));
addResult = firstPage.AddElement(imageElement2);
// add a child bookmark to this image
document.AddBookmark("RTF to PDF Converter", new ExplicitDestination(firstPage, new System.Drawing.PointF(0, 200)), firstPageBookmark);
//add a new page to document
PdfPage secondPage = document.AddPage();
//add a root bookmark to the second page
and set a 200% zoom when visiting this bookmark
ExplicitDestination secondPageDestination = new ExplicitDestination(secondPage);
secondPageDestination.ZoomPercentage = 150;
Bookmark secondPageBookmark = document.AddBookmark("Second
Page", secondPageDestination);
// display image in the available space in page and with
a auto determined height to keep the aspect ratio
ImageElement imageElement3 = new ImageElement(0, 0, System.IO.Path.Combine(imagesPath, "pdf-toolkit-pro-250.jpg"));
addResult = secondPage.AddElement(imageElement3);
// save the document on http response stream
document.Save(Response, false, "BookmarksDemo.pdf");
}
|
|
4.6 Merge and Split
|
|
The PDF Creator offers an API for merging PDF document or extracting pages from
a PDF document using MergePdf and SplitPdf classes. The code sample
below is taken from MergeSplitDemo sample application:
protected void btnCreatePDF_Click(object sender, EventArgs e)
{
string workingFolderPath = System.IO.Path.Combine(Server.MapPath("~"), "Files");
string firstFilePath = System.IO.Path.Combine(workingFolderPath, "oss.pdf");
string secondFilePath = System.IO.Path.Combine(workingFolderPath, "google.pdf");
string mergedFilePath = System.IO.Path.Combine(workingFolderPath, "MergeFileResult.pdf");
string extractedFilePath = System.IO.Path.Combine(workingFolderPath, "SplitFileResult.pdf");
// merge files into disk file
string[] filesToMerge = new string[2];
filesToMerge[0] = firstFilePath;
filesToMerge[1] = secondFilePath;
// merge the two files into mergedFilePath on disk
MergePdf.Merge(filesToMerge, mergedFilePath);
// extract first page from the merged document
and create a PDF file with it
SplitPdf.ExtractPages(mergedFilePath, 0, 1, extractedFilePath);
//merge streams
System.IO.FileStream fs1 = new System.IO.FileStream(firstFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.FileStream fs2 = new System.IO.FileStream(secondFilePath, System.IO.FileMode.Open, System.IO.FileAccess.Read);
System.IO.Stream[] streamsToMerge = new System.IO.Stream[2];
streamsToMerge[0] = fs1;
streamsToMerge[1] = fs2;
// prepare Response
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=MergeStreamsResult.pdf");
Response.AddHeader("content-type", "application/pdf" );
//Save the merge result directly on the Response stream
to browser
MergePdf.Merge(streamsToMerge, Response.OutputStream);
//send buffered output to client browser
Response.End();
// close the source streams
fs1.Close();
fs2.Close();
}
|
5. Licensing
|
|
A unique license key string is generated for each purchase. In order to unlock the
PDF Creator product you have to set the LicenseKey static
property of the LicensingManager class with the license
key string you have received after the product purchase before saving a PDF document.
The license key contains the information about the purchased product like the product
version and license type and is uniquely associated with an order ID. More details
about the license types and pricing can be found on the Buy Now page of our website.
|
|
|
|