下载-ItextSharp时生成空白pdf [英] Generating blank pdf when downloaded -ItextSharp

查看:95
本文介绍了下载-ItextSharp时生成空白pdf的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试生成一个简单的PDF文档,可以从asp.net网页下载。此pdf文档具有带标题文本的段落,其余内容已通过预填充的DataTable实例填充。我试图在这里打印的所有列都是文本,除了一列是图像(缩略图)。

I am trying to generate a simple PDF document, which can be downloadable from an asp.net webpage. This pdf document has a paragraph with a heading text and the rest of the content is been populated through a pre-filled DataTable instance. All columns, which I am trying to print here are text with an exception of one column being an image (thumbnail).

我可以执行附加的代码,没有例外,将生成pdf文档并将其下载到客户端浏览器。

I can execute the attached code with no exceptions, the pdf document will be generated and downloaded to client browser.

问题: 用户可以在浏览器中查看此下载的pdf(仅通过IE和Chrome测试)并可以查看所有内容在pdf中包括缩略图。但是,当所有pdf页面将生成的pdf保存到本地驱动器并打开它时,所有这些页面都是空白的。

一段时间以来一直在打扰我的脑袋任何提示都会非常有用。

Have been breaking my head for a while and any hint would be really helpful.

在服务器端事件中生成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));
                }
            }
        }

推荐答案

您正在混淆所有内容,这可能会让您感到有些困惑。将你想做的事情分成他们自己的功能。

You are mixing everything up so it may get a little confusing. separate what you want to do into their own functions.

这种方法的唯一责任是创建PDF

The single responsibility of this method is to Create the 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();
    }
}

这将允许你的下载更精益

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

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

By separating the responsibilities out you will notice where your mistake was in your original post. The document was flushed and closed completely before being sent in the response. This should allow for when you try to save the document that it has all the data it needs to save the complete document.

这篇关于下载-ItextSharp时生成空白pdf的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆