Hi v@run,
Using the below artixle i have created the example.
Namespaces
using System.IO;
using System.Linq;
using System.Web.Mvc;
using iTextSharp.text;
using iTextSharp.text.pdf;
using iTextSharp.tool.xml;
Controller
public class HomeController : Controller
{
// GET: /Home/
public ActionResult Index()
{
NorthwindEntities entities = new NorthwindEntities();
return View(from customer in entities.Customers.Take(10)
select customer);
}
[HttpPost]
[ValidateInput(false)]
public ActionResult Export(string GridHtml)
{
byte[] bytes;
using (MemoryStream stream = new System.IO.MemoryStream())
{
StringReader sr = new StringReader(GridHtml);
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);
pdfDoc.Open();
XMLWorkerHelper.GetInstance().ParseXHtml(writer, pdfDoc, sr);
pdfDoc.Close();
bytes = stream.ToArray();
}
string filePath = Server.MapPath("~/Content/Document/Contract.pdf");
System.IO.File.WriteAllBytes(filePath, bytes);
return RedirectToAction("Index");
}
}
View
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Index</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript">
$(function () {
$("#btnSubmit").click(function () {
$("input[name='GridHtml']").val($("#Grid").html().trim());
});
});
</script>
</head>
<body>
<div id="Grid">
<table cellpadding="5" cellspacing="0" style="border: 1px solid #ccc; font-size: 9pt;">
<tr>
<th style="background-color: #B8DBFD; border: 1px solid #ccc">
ID
</th>
<th style="background-color: #B8DBFD; border: 1px solid #ccc">
Name
</th>
<th style="background-color: #B8DBFD; border: 1px solid #ccc">
City
</th>
<th style="background-color: #B8DBFD; border: 1px solid #ccc">
Country
</th>
</tr>
<% foreach (var item in Model)
{ %>
<tr>
<td style="width: 120px; border: 1px solid #ccc">
<%: item.CustomerID %>
</td>
<td style="width: 120px; border: 1px solid #ccc">
<%: item.ContactName %>
</td>
<td style="width: 120px; border: 1px solid #ccc">
<%: item.City %>
</td>
<td style="width: 120px; border: 1px solid #ccc">
<%: item.Country %>
</td>
</tr>
<% } %>
</table>
</div>
<br />
<% using (Html.BeginForm("Export", "Home", FormMethod.Post))
{%>
<input type="hidden" name="GridHtml" />
<input type="submit" id="btnSubmit" value="Export" />
<% } %>
</body>
</html>
Screenshot
Web Page
The saved PDF