← Tüm yazılar

iTextSharp Kullanımına İlişkin Örnek Kod

Merhaba Arkadaşlar,

C# dilinde iTextSharp’ı referans alarak kullanabileceğimiz örnek kodu sizinle aşağıda paylaşıyorum. Buradaki mantık önce datatable’i html’e çeviriyoruz, ardından html’i pdf’e çeviriyoruz. Umarım anlatabilmişimdir. Kolay gelsin 🙂

DataTable to HTML

[sourcecode language=”csharp” title=”DataTable to HTML”]
public static string ConvertDataTableToHTML(DataTable dt)
{
string html = "<table style=width:100%>";
for (int i = 0; i < dt.Rows.Count; i++)
{
html += "<tr align=justify>";
for (int j = 0; j < dt.Columns.Count; j++)
html += "<td>" + dt.Rows[i][j].ToString() + "</td>";
html += "</tr>";
}
html += "</table>";
return html;
}
[/sourcecode]

HTML to PDF

[sourcecode language=”csharp” title=”HTML to PDF”]

public static void ExportToPDF(string html, string filename)
{
HttpContext context = HttpContext.Current;
context.Response.Clear();
context.Response.ContentType = "application/pdf";
context.Response.AddHeader("content-disposition", "attachment;filename=" + filename + "");
context.Response.Cache.SetCacheability(HttpCacheability.NoCache);
string str = html;
StringReader sr = new StringReader(str);
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 100f, 0.0f);
HTMLWorker htmlparser = new HTMLWorker(pdfDoc);
PdfWriter.GetInstance(pdfDoc, context.Response.OutputStream);
pdfDoc.Open();
htmlparser.Parse(sr);
pdfDoc.Close();
context.Response.Write(pdfDoc);
context.Response.End();
}
[/sourcecode]

Bir yanıt yazın

E-posta adresiniz yayınlanmayacak. Gerekli alanlar * ile işaretlenmişlerdir