Generating PDF from a DataGridView in Winforms

18 篇文章 1 订阅

https://stackoverflow.com/questions/13587520/generating-pdf-from-a-datagridview-in-winforms/22197268#22197268

I'm attempting to create a PDF from a DataGridView populated from a database.

I have just started trying to learn how to use iTextSharp to accomplish this.

The result of my code is a PDF that will not open. I get an error saying "File cannot be opened"

Here is my code to generate the PDF

void SendToPDF(string heading, string filename)
    {
        try
        {
            Document doc = new Document(PageSize.A4.Rotate(), 30, 30, 20, 20);

            string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            if (!Directory.Exists(myDocs + @"\Production Reports"))
                Directory.CreateDirectory(myDocs + @"\Production Reports");

            PdfWriter.GetInstance(doc, new FileStream(myDocs + @"\Production Reports\" + filename + ".pdf", FileMode.Append, FileAccess.Write));

            iTextSharp.text.Font titleFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14.0F, iTextSharp.text.Font.BOLD, BaseColor.BLACK);

            iTextSharp.text.Font tableFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12.0F, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);

            iTextSharp.text.Font headerfont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12.0F, iTextSharp.text.Font.BOLD, BaseColor.BLACK);

            PdfPTable table = new PdfPTable(GridView.Columns.Count);
            //table.TotalWidth = GridView.Width;

            //There are ALWAYS 10 columns

            float[] widths = new float[] { GridView.Columns[0].Width, GridView.Columns[1].Width, GridView.Columns[2].Width, 
                                           GridView.Columns[3].Width, GridView.Columns[4].Width, GridView.Columns[5].Width,
                                           GridView.Columns[6].Width, GridView.Columns[7].Width, GridView.Columns[8].Width,
                                           GridView.Columns[9].Width };
            table.SetWidths(widths);
            table.HorizontalAlignment = 1; // 0 - left, 1 - center, 2 - right;
            table.SpacingBefore = 2.0F;

            PdfPCell cell = null;

            doc.Open();
            Phrase p = new Phrase(new Chunk(heading, titleFont));
            doc.Add(p);

            foreach (DataGridViewColumn c in GridView.Columns)
            {
                cell = new PdfPCell(new Phrase(new Chunk(c.HeaderText, headerfont)));
                cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
                table.AddCell(cell);
            }

            if (GridView.Rows.Count > 0)
            {
                for (int i = 0; i < GridView.Rows.Count - 1; i++)
                {
                    for (int j = 0; j < GridView.Columns.Count - 1; j++)
                    {
                        cell = new PdfPCell(new Phrase(GridView.Rows[i].Cells[j].Value.ToString(), tableFont));
                        cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                        cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
                        table.AddCell(cell);
                    }
                }
            }
            doc.Add(table);
            doc.Close();
        }
        catch (Exception ex)
        {
            MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace, "Error Generating PDF", MessageBoxButtons.OK, MessageBoxIcon.Error);
        }
    }

I'm guessing my problem has to do with setting column widths, but I'm not sure. One time, and only one time..I saw an error when I tried to open the PDF that said "illegal floating point division by 0" or something along those lines.

Any help is greatly appreciated.

c# pdf-generation itextsharp

shareimprove this question

asked Nov 27 '12 at 15:30

 

CSharpDev

8191010 silver badges2121 bronze badges

add a comment

2 Answers

activeoldestvotes

2

 

It may sound obvious, but your program isn't running and locking the pdf file to its process thus preventing adobe pdf reader from reading it is it?

shareimprove this answer

answered Nov 27 '12 at 15:55

 

Daniel Lane

2,2041414 silver badges3333 bronze badges

add a comment

-1

 

private void jbtnPdf_Click(object sender, EventArgs e) { try {

            SaveFileDialog saveFileDialog = new SaveFileDialog();
            saveFileDialog.Filter = "All Files | *.*  ";
            if (saveFileDialog.ShowDialog() == DialogResult.OK)
            {

                string path = saveFileDialog.FileName;

                Document pdfdoc = new Document(PageSize.A4); // Setting the page size for the PDF




                PdfWriter writer = PdfWriter.GetInstance(pdfdoc, new FileStream(path + ".pdf", FileMode.Create)); //Using the PDF Writer class to generate the PDF
                writer.PageEvent = new PDFFooter();
                 // Opening the PDF to write the data from the textbox


                PdfPTable table = new PdfPTable(jdgvChild.Columns.Count);
                //table.TotalWidth = GridView.Width;



                float[] widths = new float[] { jdgvChild.Columns[0].Width, jdgvChild.Columns[1].Width, jdgvChild.Columns[2].Width, 
                                       jdgvChild.Columns[3].Width, jdgvChild.Columns[4].Width, jdgvChild.Columns[5].Width,
                                       jdgvChild.Columns[6].Width, jdgvChild.Columns[7].Width};
                table.SetWidths(widths);
                table.HorizontalAlignment = 1; // 0 - left, 1 - center, 2 - right;
                table.SpacingBefore = 2.0F;

                PdfPCell cell = null;
                pdfdoc.Open();





                //doc.Open();
             //   Phrase p = new Phrase(new Chunk(heading, titleFont));
               // doc.Add(p);

                foreach (GridViewDataColumn c in jdgvChild.Columns)
                {
                    cell = new PdfPCell(new Phrase(new Chunk(c.HeaderText)));

                    cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                    cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
                    table.AddCell(cell);
                }


                if (jdgvChild.Rows.Count > 0)
                {
                   for (int i = 0; i < jdgvChild.Rows.Count; i++)
                    {

                    PdfPCell[] objcell = new PdfPCell[jdgvChild.Columns.Count];

                        for (int j = 0; j < jdgvChild.Columns.Count-1; j++)
                        {

                            cell = new PdfPCell(new Phrase(jdgvChild.Rows[i].Cells[j].Value.ToString()));
                            cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
                            cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
                           // table.AddCell(cell);
                            //lstCells.Add(cell);
                            objcell[j] = cell;
                        }
                        PdfPRow newrow = new PdfPRow(objcell);
                        table.Rows.Add(newrow);
                    }
                }



                pdfdoc.Add(table);

                MessageBox.Show("Pdf Generation Successfully.");
              pdfdoc.Close();
            }
        }
         catch (Exception ex)
        {
            MessageBox.Show("Error in pdf Generation.");
        }
    }

shareimprove this answer

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值