Background
I was recently developing a site which needed to produce PDF documents automatically based on HTML content. The HTML originated from a variety of other sites and I needed to consolidate the content into a single PDF file. The challenge was that the full HTML was fairly large and the PDF file needed to be created quickly.
I was doing all the development work in .NET and C# so I starting looking at various .NET modules which could help me accomplish the task. I looked at several different products such as iTextSharp and I wanted a product that was easy to use and also a product that could create a PDF which interpreted the HTML styling in a proper way. After spending several hours testing a variety of products, I found a product from webSupergoo called ABCPdf .NET. I got it working within minutes and it is, in my opinion, the best product for creating a PDF file based on HTML content. The PDF files correctly interpret all the styling information in the HTML, including CSS directives.
One of the advantages with ABCPdf .NET is that it is fairly cheap with regards to the functionality it offers. Licenses for ABCpdf .NET only costs $329 per installed copy. The API is easy to learn and one of the best things with the product is that they offer very good support. I’ve asked for assistance with some of the more complex development tasks that I’ve had and I’ve always received an answer within 24 hrs. The answers have also typically included a code sample.
More info about ABCPdf can be found at
Websupergoo
Using the Code
I want to show you how I used ABCPdf .NET to process HTML, add page numbers to each page and then save the generated PDF file. The page number needed to be added at the bottom of the page and also below the content. I wanted to add a separator line below the content and then add the page number just below the separator line. I intended on printing the PDF double sided which meant that the page number needed to be right-aligned on the first page, left-aligned on the second and so on.
string HTML_STRING;
var streamReader = new StreamReader(@"c:\html.txt");
HTML_STRING = streamReader.ReadToEnd();
streamReader.Close();
var theDoc = new Doc();
theDoc.TextStyle.Size = 20;
theDoc.Rect.Inset(40, 55);
theDoc.Color.String = "255 255 255";
int theId = theDoc.AddImageHtml(HTML_STRING);
while (true)
{
theDoc.FrameRect();
if (!theDoc.Chainable(theId))
break;
theDoc.Page = theDoc.AddPage();
theId = theDoc.AddImageToChain(theId);
}
theDoc.HtmlOptions.LinkPages();
theDoc.Rect.String = "35 30 580 50";
theDoc.Font = theDoc.AddFont("Trebuchet");
theDoc.FontSize = 11;
int pagenumber = 1;
for (int i = 1; i <= theDoc.PageCount; i++)
{
theDoc.PageNumber = i;
string txt = pagenumber.ToString();
theDoc.Color.String = "169 169 169";
theDoc.VPos = 1.0;
if ((i%2) == 0)
{
theDoc.HPos = 0.01;
}
else
{
theDoc.HPos = 0.99;
}
theDoc.AddText(txt);
theDoc.AddLine(21, 55, 590, 55);
theDoc.Flatten();
pagenumber++;
}
theDoc.Save(@"c:\pdf.pdf");
theDoc.Clear();