itext - 在 Web API 中将数十万条数据表记录转换为 PDF
问题描述
我正在尝试使用 ADO.Net 从 Web api 中的 DataTable 创建 PDF。不幸的是,有时基于过滤器,我可能会获得非常少的记录并且能够毫无问题地下载。有时可能非常庞大,例如 20 万条记录。当我在本地检查我的系统时,它在将 dt 转换为 PDF 时挂起。我的代码如下:
private FileContentResult ExportPDF(DataTable dataTable)
{
string Name = "Logs";
System.IO.MemoryStream mStream = new System.IO.MemoryStream();
byte[] content = null;
try
{
string[] columnNames = (from dc in dataTable.Columns.Cast<DataColumn>() select dc.ColumnName).ToArray();
int count = columnNames.Length;
object[] array = new object[count];
dataTable.Rows.Add(array);
Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
PdfWriter writer = PdfWriter.GetInstance(pdfDoc, mStream);
int cols = dataTable.Columns.Count;
int rows = dataTable.Rows.Count;
HeaderFooter header = new HeaderFooter(new Phrase(Name), false);
// Remove the border that is set by default
header.Border = iTextSharp.text.Rectangle.TITLE;
// Align the text: 0 is left, 1 center and 2 right.
header.Alignment = Element.ALIGN_CENTER;
pdfDoc.Header = header;
// Header.
pdfDoc.Open();
iTextSharp.text.Table pdfTable = new iTextSharp.text.Table(cols, rows);
pdfTable.BorderWidth = 1; pdfTable.Width = 100;
pdfTable.Padding = 1; pdfTable.Spacing = 4;
//creating table headers
for (int i = 0; i < cols; i++)
{
Cell cellCols = new Cell();
Chunk chunkCols = new Chunk();
iTextSharp.text.Font ColFont = FontFactory.GetFont(FontFactory.HELVETICA, 14, iTextSharp.text.Font.BOLD, iTextSharp.text.BaseColor.Black);
chunkCols = new Chunk(dataTable.Columns[i].ColumnName, ColFont);
cellCols.Add(chunkCols);
pdfTable.AddCell(cellCols);
}
//creating table data (actual result)
for (int k = 0; k < rows; k++)
{
for (int j = 0; j < cols; j++)
{
Cell cellRows = new Cell();
iTextSharp.text.Font RowFont = FontFactory.GetFont(FontFactory.HELVETICA, 12);
Chunk chunkRows = new Chunk(dataTable.Rows[k][j].ToString(), RowFont);
cellRows.Add(chunkRows);
pdfTable.AddCell(cellRows);
}
}
pdfDoc.Add(pdfTable);
pdfDoc.Close();
content = mStream.ToArray();
return File(content, "application/pdf", "LogReports.pdf");
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
}
解决方案
推荐阅读
- sql - 电子邮件重复百分比计算
- excel - Excel列自动计算
- asp.net-core - ResponseCache 可以仅因 cookie 值而异吗?
- java - 如何将一个节点链插入另一个节点链
- snakemake - 当上游规则失败时,Snakemake 如何执行下游规则
- javascript - 我不能正确使用光滑的滑块,它没有显示任何结果
- git - 在 intellij 的帮助下,git 克隆 bitbucket 中存在的所有 git 存储库
- google-apps-script - 如何将驱动器中的脚本应用程序链接到我的谷歌表
- lisp - 在 Lisp 中具有初始元素的列表从 99 到 0 开始
- javascript - 单击后如何删除角度分量?