Last active
August 29, 2015 14:17
-
-
Save MiniverCheevy/7c4275410c2d93084321 to your computer and use it in GitHub Desktop.
iTextSharp html to pdf
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Data.Entity.Core.Mapping; | |
using System.IO; | |
using System.Linq; | |
using System.Text; | |
using System.Threading.Tasks; | |
using iTextSharp.text; | |
using iTextSharp.text.pdf; | |
using iTextSharp.tool.xml; | |
using Voodoo; | |
namespace Helpers | |
{ | |
public class PdfGenerator | |
{ | |
public static Byte[] GeneratePdfFromFragment(string htmlFragment) | |
{ | |
var html = string.Format(@" | |
<html xmlns='http://www.w3.org/1999/xhtml' xml:lang='en'> | |
<head> | |
<style type='text/css'> | |
table,td {{border: 1px solid black;}} | |
div {{ white-space: nowrap; padding: 2px;}} | |
table{{ border-collapse: collapse; width: 100%; empty-cells: show;}} | |
body table {{font-size: 50%;}} | |
th {{width:500px; height: 28px;}} | |
td {{width:300px; height: 28px;}} | |
</style> | |
</head><body>{0}</body></html>", htmlFragment); | |
return generate(html); | |
} | |
public static Byte[] GeneratePdfFromPage(string htmlPage) | |
{ | |
return generate(htmlPage); | |
} | |
private static Byte[] generate (string html) | |
{ | |
using (var memoryStream = new MemoryStream()) | |
{ | |
var pdfDocument = new Document(PageSize.LETTER); | |
var pdfWriter = PdfWriter.GetInstance(pdfDocument, memoryStream); | |
pdfDocument.Open(); | |
using (var fw = new StringReader(html)) | |
{ | |
XMLWorkerHelper.GetInstance().ParseXHtml(pdfWriter, pdfDocument, fw); | |
pdfDocument.Close(); | |
fw.Close(); | |
} | |
return memoryStream.ToArray(); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment