Tech
News
Videos
Forums
Jobs
Books
Events
More
Interviews
Live
Learn
Training
Career
Members
Blogs
Challenges
Certification
Contribute
Article
Blog
Video
Ebook
Interview Question
Collapse
Feed
Dashboard
Wallet
Learn
Achievements
Network
Rewards
SharpGPT
Premium
Contribute
Article
Blog
Video
Ebook
Interview Question
Register
Login
Download Webgrid Data in a PDF file with MVC 5
WhatsApp
Malvik Bhavsar
10y
20.3
k
0
2
25
Blog
In previous article I explained
d
ispla
y data In webgrid and delete multiple rows by using checkboxes
.
Now i will explain how to download that data in a pdf file.
So first check previous
article
and add Action Link in list.cshtml for Create PDF.
Create PDF : @Html.ActionLink(
"Create PDF"
,
"CreatePdf"
,
"Home"
)
Go to Solution Explorer > Right Click on References > Manage NuGet Packages...> Search with itextsharp text > Install this 2 dll.
Now Add CreatePdf Action into Home Controller and also add following namespace.
using
iTextSharp.text;
using
iTextSharp.text.pdf;
using
System.IO;
using
System.Web.Helpers;
Now Add CreatePdf Action code.
public
FileStreamResult CreatePdf()
{
List all =
new
List();
all = db.Employees.ToList();
WebGrid grid =
new
WebGrid(source: all, canPage:
false
, canSort:
false
);
string
gridHtml = grid.GetHtml(
columns: grid.Columns(
grid.Column(
"Id"
,
"EmployeeId"
),
grid.Column(
"Name"
,
"Employee Name"
),
grid.Column(
"City"
,
"City"
),
grid.Column(
"MobileNo"
,
"Mobile No"
)
)
).ToString();
string
exportData = String.Format(
"{0}{1}"
,
""
, gridHtml);
var bytes = System.Text.Encoding.UTF8.GetBytes(exportData);
using
(var input =
new
MemoryStream(bytes))
{
var output =
new
MemoryStream();
var document =
new
iTextSharp.text.Document(PageSize.A4, 50, 50, 50, 50);
var writer = PdfWriter.GetInstance(document, output);
writer.CloseStream =
false
;
document.Open();
var xmlWorker = iTextSharp.tool.xml.XMLWorkerHelper.GetInstance();
xmlWorker.ParseXHtml(writer, document, input, System.Text.Encoding.UTF8);
document.Close();
output.Position = 0;
return
new
FileStreamResult(output,
"application/pdf"
);
}
}
RUN APPLICATION(CTTL + F5).
Click on Create PDF. and get PDF.
Download Webgrid data in a pdf file with MVC5
Up Next
How To Open PDF File In New Tab In MVC Using C#
Ebook Download
View all
Diving Into ASP.NET WebAPI
Read by 21.5k people
Download Now!
Learn
View all
Membership not found