簡體   English   中英

從Winforms中的DataGridView生成PDF

[英]Generating PDF from a DataGridView in Winforms

我正在嘗試從數據庫中填充的DataGridView創建PDF。

我剛開始嘗試學習如何使用iTextSharp來實現這一目標。

我的代碼的結果是一個無法打開的PDF。 我收到錯誤消息“文件無法打開”

這是我生成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);
        }
    }

我猜我的問題與設置列寬有關,但我不確定。 有一次,只有一次..當我試圖打開“非法浮點除0”或類似的東西時,我看到了一個錯誤。

任何幫助是極大的贊賞。

聽起來很明顯,但你的程序沒有運行並將pdf文件鎖定到它的進程,從而阻止了adobe pdf閱讀器的閱讀呢?

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM