Within the context of projects is normal the need to generate reports , basically as the level of detail increases, complexity of the report also increases. Hence the need to incorporate images into texts, or tables into images or even all together.
So I'm going to suggest a response to the transformation from HTML to PDF, so that the code can be reusable and without the need to have to change library or plugins, besides the fact that the PDF is for the most part composed of Post Script .
In other words, PDF is basically an Image.
There is a free library called iTextSharp , I already used and solved a similar problem I had.
Example how to use :
//Cria um array de bytes para salvar os dados do PDF
Byte[] bytes;
//Para evitar preocupação com alocação de memória e etc...
using (var ms = new MemoryStream()) {
//Cria um documento abstrato
using (var doc = new Document()) {
//Cria um escritor para bindar os dados no documento abstrato
using (var writer = PdfWriter.GetInstance(doc, ms)) {
//Abre o documento abstrato
doc.Open();
//Insere o HTML e o CSS como string ou como variável
var example_html = @"<body><p>This is a shitty html code</p><p>This is another html line</p></body>";
var example_css = @"CSS AQUI";
//Converte as strings do HTML e CSS
using (var msCss = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_css))) {
using (var msHtml = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(example_html))) {
//Faz o Parse do HTML
iTextSharp.tool.xml.XMLWorkerHelper.GetInstance().ParseXHtml(writer, doc, msHtml, msCss);
}
}
//Fecha o documento
doc.Close();
}
}
//Fecha MemoryStream e joga dentro do array de bytes
bytes = ms.ToArray();
}
//Transfere o array para o disco
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "download.pdf");
System.IO.File.WriteAllBytes(testFile, bytes);
Now if what you really want is an image, simply do:
//Realiza uma iteração para cada página
for(int i=0;i< pdfdocument.Pages.Count;i++)
{
//Salva a página como imagem
System.Drawing.Image image= pdfdocument.SaveAsImage(i, 96, 96);
image.Save(string.Format("ImagePage{0}.png", i), System.Drawing.Imaging.ImageFormat.Png);
}
Reference