下载-ItextSharp时生成空白pdf

时间:2016-06-21 21:53:44

标签: c# asp.net itext

我正在尝试生成一个简单的PDF文档,可以从asp.net网页下载。此pdf文档具有带标题文本的段落,其余内容已通过预填充的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类的一部分)

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));
                }
            }
        }

ItextSharp Dll Version Info

1 个答案:

答案 0 :(得分:3)

你正在混合所有东西,所以它可能会有点混乱。将你想做的事情分成他们自己的功能。

此方法的唯一责任是创建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);
}

通过将责任分开,您将会注意到您的错误在原始帖子中的位置。在回复中发送文档之前,文档已完全刷新并关闭。当您尝试保存文档时,它应该允许它具有保存整个文档所需的所有数据。