|
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="StandardPdfRenderer.cs" company="SemanticArchitecture">
// http://www.SemanticArchitecture.net
// </copyright>
// <summary>
// This class is responsible for rendering a html text string to a PDF document
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace ReportManagement
{
using System.IO;
using iTextSharp.text;
using iTextSharp.text.html.simpleparser;
using iTextSharp.text.pdf;
/// <summary>
/// This class is responsible for rendering a html text string to a PDF document using the html renderer of iTextSharp.
/// </summary>
public class StandardPdfRenderer
{
private const int HorizontalMargin = 40;
private const int VerticalMargin = 40;
public byte[] Render(string htmlText, string pageTitle)
{
byte[] renderedBuffer;
using (var outputMemoryStream = new MemoryStream())
{
using (var pdfDocument = new Document(PageSize.A4, HorizontalMargin, HorizontalMargin, VerticalMargin, VerticalMargin))
{
PdfWriter pdfWriter = PdfWriter.GetInstance(pdfDocument, outputMemoryStream);
pdfWriter.CloseStream = false;
pdfWriter.PageEvent = new PrintHeaderFooter { Title = pageTitle };
pdfDocument.Open();
using (var htmlViewReader = new StringReader(htmlText))
{
using (var htmlWorker = new HTMLWorker(pdfDocument))
{
htmlWorker.Parse(htmlViewReader);
}
}
}
renderedBuffer = new byte[outputMemoryStream.Position];
outputMemoryStream.Position = 0;
outputMemoryStream.Read(renderedBuffer, 0, renderedBuffer.Length);
}
return renderedBuffer;
}
}
}
|
By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.
If a file you wish to view isn't highlighted, and is a text file (not binary), please
let us know and we'll add colourisation support for it.
Patrick Kalkman is a senior Software Architect with more than 20 years professional development experience. He works for
SimpleTechture where he helps teams develop state of the art web applications.
Patrick enjoys writing his
blog. It discusses agile software development. Patrick can be reached at patrick@simpletechture.nl.
Published Windows 8 apps:
Published Windows Phone apps:
Awards:
Best Mobile article of March 2012
Best Mobile article of June 2012