Hi @Gani_tpt,
You can't "convert" a DataTable to a PDF Document. But you can insert data into it as normal content.
The specific code is as follows:
public void ExportToPdf()
{
DataTable dt = (DataTable)ViewState["FinalData"];
MemoryStream mStream = new MemoryStream();
Document document = new Document();
PdfWriter writer = PdfWriter.GetInstance(document, mStream);
document.Open();
PdfPTable pdfTable = new PdfPTable(dt.Columns.Count);
pdfTable.WidthPercentage = 100;
// Add table headers
for (int i = 0; i < dt.Columns.Count; i++)
{
PdfPCell cell = new PdfPCell(new Phrase(dt.Columns[i].ColumnName));
cell.BackgroundColor = BaseColor.LIGHT_GRAY;
pdfTable.AddCell(cell);
}
// Add table rows
for (int row = 0; row < dt.Rows.Count; row++)
{
for (int column = 0; column < dt.Columns.Count; column++)
{
pdfTable.AddCell(dt.Rows[row][column].ToString());
}
}
document.Add(pdfTable);
document.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.BinaryWrite(mStream.ToArray());
Response.End();
}
HTMLWorker is obsolete
This is not an error message, just a warning message.
Obsolete means it is not being used now. But still you can use it.
You can use XmlWorkerHelper class instead of HtmlWorker to convert HTML string to PDF.
Run the command below in the Package Manager Console.
Install-Package iTextSharp.xmlworker
But this method doesn't apply to your problem, I just add it here.
Best regards,
Lan Huang
If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".
Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.