下载时生成空白pdf-ItextSharp
Generating blank pdf when downloaded -ItextSharp
我正在尝试生成一个简单的 PDF 文档,可以从 asp.net 网页下载该文档。此 pdf 文档有一段带有标题文本,其余内容通过 pre-filled DataTable 实例填充。我在这里尝试打印的所有栏都是文本,但一栏是图像(缩略图)。
我可以毫无例外地执行附件代码,pdf文档将生成并下载到客户端浏览器。
问题: 用户可以在他们的浏览器中查看这个下载的 pdf(仅使用 IE 和 Chrome 测试)并且可以在pdf 包括缩略图。但是,当他们将此生成的 pdf 保存到本地驱动器并打开它时,所有 pdf 页面都是空白的。
让我头疼了一段时间,任何提示都会很有帮助。
在服务器端事件生成 PDF 的代码
private void Download()
{
var document = new Document();
try
{
var dataTable = GetDataTable(parameters); //this line create and fill a DataTable with some values
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition","attachment;filename=sample.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);//get a pdf writer instance
document.Open();
//Create table
var pdfTable = DocumentManager.CreateTable(dataTable.Columns.Count, new[] { 30f, 130f, 130f, 80f, 60f, 80f, 60f, 80f, 60f, 60f, 80f, 80f, 60f });
//Create a simple heading
var heading = new StringBuilder();
heading.AppendLine("Summary");
var contentFont = DocumentManager.GetFont(5);
var genHeadingFont = DocumentManager.GetFont(6, true);
var image = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("/images/some.png"));
image.WidthPercentage = 25;
image.Alignment = iTextSharp.text.Image.ALIGN_RIGHT;
document.Add(image);
document.Add(new Paragraph(heading.ToString(), contentFont));
//Create column heading
DocumentManager.CreateColums(pdfTable, dataTable, genHeadingFont);
//Create cells and fill with values
DocumentManager.CreateCellAndFillValue(pdfTable, dataTable.Select(), contentFont, new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 });
document.Add(pdfTable);
Response.Write(document);
document.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
}
}
参考方法(DocumentManager Class 的一部分)
public static PdfPTable CreateTable(int columnSpan, float[] columnWidths)
{
var table = new PdfPTable(columnSpan);
table.SetWidths(columnWidths);
table.TotalWidth = 1000f;
table.WidthPercentage = 100;
return table;
}
public static Font GetFont(int size, bool isBold = false)
{
return FontFactory.GetFont("Calibri", size, isBold ? Font.BOLD : Font.NORMAL);
}
public static void CreateColums(PdfPTable pdfTable, DataTable dataColumns, Font columnsFont,
List<string> columnsToExclude = null, BaseColor backGround = null)
{
columnsToExclude = columnsToExclude ?? new List<string>();
foreach (
var c in
from DataColumn c in dataColumns.Columns where !columnsToExclude.Contains(c.ColumnName) select c)
{
var cell = new PdfPCell(new Phrase(c.ColumnName, columnsFont)) { BackgroundColor = backGround ?? new BaseColor(164, 183, 210), HorizontalAlignment = Element.ALIGN_MIDDLE };
cell.PaddingBottom = 3f;
cell.PaddingTop = 3f;
cell.PaddingLeft = 3f;
cell.PaddingRight = 3f;
pdfTable.AddCell(cell);
}
}
public static void CreateCellAndFillValue(PdfPTable table, DataRow[] dataRows, Font cellFont,
int[] columnIndex = null, string[] columnNames = null)
{
if (columnIndex != null && columnIndex.Length != 0)
{
CreateCellValueUsingIndex(table, dataRows, cellFont, columnIndex);
return;
}
if (columnNames != null && columnNames.Length != 0)
{
CreateCellValueUsingColumnName(table, dataRows, cellFont, columnNames);
}
}
public static void CreateCellValueUsingIndex(PdfPTable table, IEnumerable<DataRow> dataRows, Font cellFont, int[] columnIndex)
{
foreach (var r in dataRows)
{
foreach (var index in columnIndex)
{
if (index != 1) //value columns
{
var cell = new PdfPCell(new Phrase(r[index].ToString(), cellFont));
cell.PaddingBottom = 2f;
cell.PaddingTop = 2f;
cell.PaddingLeft = 2f;
cell.PaddingRight = 2f;
cell.HorizontalAlignment = Element.ALIGN_CENTER;
table.AddCell(cell);
}
else //image columns
{
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(r[index].ToString());
image.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
PdfPCell imgCell = new PdfPCell();
imgCell.AddElement(new Chunk(image, 0, 0));
table.AddCell(imgCell);
}
}
}
}
public static void CreateCellValueUsingColumnName(PdfPTable table, IEnumerable<DataRow> dataRows, Font cellFont,
string[] columnNames)
{
foreach (var r in dataRows)
{
foreach (var name in columnNames)
{
table.AddCell(new Phrase(r[name].ToString(), cellFont));
}
}
}
你把所有东西都混在一起了,所以可能会有点混乱。把你想做的事情分成各自的功能。
此方法的唯一职责是创建 PDF
private void CreatePdf(Stream output) {
var document = new Document();
try {
var dataTable = GetDataTable(parameters); //this line create and fill a DataTable with some values
//get a pdf writer instance
PdfWriter writer = PdfWriter.GetInstance(document, output);
//open the document
document.Open();
//Create table
var pdfTable = DocumentManager.CreateTable(dataTable.Columns.Count, new[] { 30f, 130f, 130f, 80f, 60f, 80f, 60f, 80f, 60f, 60f, 80f, 80f, 60f });
//Create a simple heading
var heading = new StringBuilder();
heading.AppendLine("Summary");
var contentFont = DocumentManager.GetFont(5);
var genHeadingFont = DocumentManager.GetFont(6, true);
var image = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("/images/some.png"));
image.WidthPercentage = 25;
image.Alignment = iTextSharp.text.Image.ALIGN_RIGHT;
document.Add(image);
document.Add(new Paragraph(heading.ToString(), contentFont));
//Create column heading
DocumentManager.CreateColums(pdfTable, dataTable, genHeadingFont);
//Create cells and fill with values
DocumentManager.CreateCellAndFillValue(pdfTable, dataTable.Select(), contentFont, new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 });
document.Add(pdfTable);
// make sure any data in the buffer is written to the output stream
writer.Flush();
} finally {
document.Close();
}
}
这将使您的 Download
更苗条一些
private void Download() {
Response.ContentType = "application/pdf;";
Response.AddHeader("content-disposition","attachment;filename=sample.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
// stream to store generated document
var output = new MemoryStream();
// generate document
CreatePdf(output);
// pass the generated data to the response output stream
Response.OutputStream.Write(output.GetBuffer(), 0, output.Length);
}
通过分离责任,您会发现您原来的错误在哪里 post。在响应中发送之前,文档已被刷新并完全关闭。这应该允许当您尝试保存文档时,它具有保存完整文档所需的所有数据。
我正在尝试生成一个简单的 PDF 文档,可以从 asp.net 网页下载该文档。此 pdf 文档有一段带有标题文本,其余内容通过 pre-filled DataTable 实例填充。我在这里尝试打印的所有栏都是文本,但一栏是图像(缩略图)。
我可以毫无例外地执行附件代码,pdf文档将生成并下载到客户端浏览器。
问题: 用户可以在他们的浏览器中查看这个下载的 pdf(仅使用 IE 和 Chrome 测试)并且可以在pdf 包括缩略图。但是,当他们将此生成的 pdf 保存到本地驱动器并打开它时,所有 pdf 页面都是空白的。
让我头疼了一段时间,任何提示都会很有帮助。
在服务器端事件生成 PDF 的代码
private void Download()
{
var document = new Document();
try
{
var dataTable = GetDataTable(parameters); //this line create and fill a DataTable with some values
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition","attachment;filename=sample.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
PdfWriter writer = PdfWriter.GetInstance(document, Response.OutputStream);//get a pdf writer instance
document.Open();
//Create table
var pdfTable = DocumentManager.CreateTable(dataTable.Columns.Count, new[] { 30f, 130f, 130f, 80f, 60f, 80f, 60f, 80f, 60f, 60f, 80f, 80f, 60f });
//Create a simple heading
var heading = new StringBuilder();
heading.AppendLine("Summary");
var contentFont = DocumentManager.GetFont(5);
var genHeadingFont = DocumentManager.GetFont(6, true);
var image = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("/images/some.png"));
image.WidthPercentage = 25;
image.Alignment = iTextSharp.text.Image.ALIGN_RIGHT;
document.Add(image);
document.Add(new Paragraph(heading.ToString(), contentFont));
//Create column heading
DocumentManager.CreateColums(pdfTable, dataTable, genHeadingFont);
//Create cells and fill with values
DocumentManager.CreateCellAndFillValue(pdfTable, dataTable.Select(), contentFont, new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 });
document.Add(pdfTable);
Response.Write(document);
document.Close();
}
catch (Exception ex)
{
throw ex;
}
finally
{
}
}
参考方法(DocumentManager Class 的一部分)
public static PdfPTable CreateTable(int columnSpan, float[] columnWidths)
{
var table = new PdfPTable(columnSpan);
table.SetWidths(columnWidths);
table.TotalWidth = 1000f;
table.WidthPercentage = 100;
return table;
}
public static Font GetFont(int size, bool isBold = false)
{
return FontFactory.GetFont("Calibri", size, isBold ? Font.BOLD : Font.NORMAL);
}
public static void CreateColums(PdfPTable pdfTable, DataTable dataColumns, Font columnsFont,
List<string> columnsToExclude = null, BaseColor backGround = null)
{
columnsToExclude = columnsToExclude ?? new List<string>();
foreach (
var c in
from DataColumn c in dataColumns.Columns where !columnsToExclude.Contains(c.ColumnName) select c)
{
var cell = new PdfPCell(new Phrase(c.ColumnName, columnsFont)) { BackgroundColor = backGround ?? new BaseColor(164, 183, 210), HorizontalAlignment = Element.ALIGN_MIDDLE };
cell.PaddingBottom = 3f;
cell.PaddingTop = 3f;
cell.PaddingLeft = 3f;
cell.PaddingRight = 3f;
pdfTable.AddCell(cell);
}
}
public static void CreateCellAndFillValue(PdfPTable table, DataRow[] dataRows, Font cellFont,
int[] columnIndex = null, string[] columnNames = null)
{
if (columnIndex != null && columnIndex.Length != 0)
{
CreateCellValueUsingIndex(table, dataRows, cellFont, columnIndex);
return;
}
if (columnNames != null && columnNames.Length != 0)
{
CreateCellValueUsingColumnName(table, dataRows, cellFont, columnNames);
}
}
public static void CreateCellValueUsingIndex(PdfPTable table, IEnumerable<DataRow> dataRows, Font cellFont, int[] columnIndex)
{
foreach (var r in dataRows)
{
foreach (var index in columnIndex)
{
if (index != 1) //value columns
{
var cell = new PdfPCell(new Phrase(r[index].ToString(), cellFont));
cell.PaddingBottom = 2f;
cell.PaddingTop = 2f;
cell.PaddingLeft = 2f;
cell.PaddingRight = 2f;
cell.HorizontalAlignment = Element.ALIGN_CENTER;
table.AddCell(cell);
}
else //image columns
{
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(r[index].ToString());
image.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
PdfPCell imgCell = new PdfPCell();
imgCell.AddElement(new Chunk(image, 0, 0));
table.AddCell(imgCell);
}
}
}
}
public static void CreateCellValueUsingColumnName(PdfPTable table, IEnumerable<DataRow> dataRows, Font cellFont,
string[] columnNames)
{
foreach (var r in dataRows)
{
foreach (var name in columnNames)
{
table.AddCell(new Phrase(r[name].ToString(), cellFont));
}
}
}
你把所有东西都混在一起了,所以可能会有点混乱。把你想做的事情分成各自的功能。
此方法的唯一职责是创建 PDF
private void CreatePdf(Stream output) {
var document = new Document();
try {
var dataTable = GetDataTable(parameters); //this line create and fill a DataTable with some values
//get a pdf writer instance
PdfWriter writer = PdfWriter.GetInstance(document, output);
//open the document
document.Open();
//Create table
var pdfTable = DocumentManager.CreateTable(dataTable.Columns.Count, new[] { 30f, 130f, 130f, 80f, 60f, 80f, 60f, 80f, 60f, 60f, 80f, 80f, 60f });
//Create a simple heading
var heading = new StringBuilder();
heading.AppendLine("Summary");
var contentFont = DocumentManager.GetFont(5);
var genHeadingFont = DocumentManager.GetFont(6, true);
var image = iTextSharp.text.Image.GetInstance(HttpContext.Current.Server.MapPath("/images/some.png"));
image.WidthPercentage = 25;
image.Alignment = iTextSharp.text.Image.ALIGN_RIGHT;
document.Add(image);
document.Add(new Paragraph(heading.ToString(), contentFont));
//Create column heading
DocumentManager.CreateColums(pdfTable, dataTable, genHeadingFont);
//Create cells and fill with values
DocumentManager.CreateCellAndFillValue(pdfTable, dataTable.Select(), contentFont, new[] { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12 });
document.Add(pdfTable);
// make sure any data in the buffer is written to the output stream
writer.Flush();
} finally {
document.Close();
}
}
这将使您的 Download
更苗条一些
private void Download() {
Response.ContentType = "application/pdf;";
Response.AddHeader("content-disposition","attachment;filename=sample.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
// stream to store generated document
var output = new MemoryStream();
// generate document
CreatePdf(output);
// pass the generated data to the response output stream
Response.OutputStream.Write(output.GetBuffer(), 0, output.Length);
}
通过分离责任,您会发现您原来的错误在哪里 post。在响应中发送之前,文档已被刷新并完全关闭。这应该允许当您尝试保存文档时,它具有保存完整文档所需的所有数据。