0

我在 C# 中有一个面板,其中包含各种组件,如图片框和数据网格视图。我希望创建一个包含整个 datagridview 和图片框的 pdf。目前,只有 datagridview 或图片框出现在 pdf 中。将两者合并在一起是不可能的。我正在使用 iTextSharp 创建 pdf。我的代码如下..

        string strFileName;

        string FontPath = "C:\\WINDOWS\\Fonts\\simsun.ttc,1";

        int FontSize = 12;

        ///

        Boolean cc = false;
        SaveFileDialog savFile = new SaveFileDialog();
        savFile.AddExtension = true;
        savFile.DefaultExt = "pdf";
        savFile.Filter = "PDF Document|*.pdf|*.pdf|";

        savFile.ShowDialog();

        if (savFile.FileName != "")
        {
            strFileName = savFile.FileName;
        }
        else
        {
            MessageBox.Show("export stop", "export stop", MessageBoxButtons.OK, MessageBoxIcon.Information);
            return;
        }


        iTextSharp.text.Image jpg= iTextSharp.text.Image.GetInstance(Properties.Resources.templete3, System.Drawing.Imaging.ImageFormat.Png);

        jpg.ScaleToFit(750, 850);
        jpg.SetAbsolutePosition(0, 0);

        // Page site and margin left, right, top, bottom is defined
        Document pdfDoc = new Document(PageSize.A4);//, 10f, 10f, 10f, 0f);


        //If you want to choose image as background then,



        PdfWriter writer = PdfWriter.GetInstance(pdfDoc, new FileStream(strFileName, FileMode.Create));

        BaseFont baseFont = BaseFont.CreateFont(FontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);

        iTextSharp.text.Font font = new iTextSharp.text.Font(baseFont, FontSize);

        pdfDoc.Open();

        PdfPTable table = new PdfPTable(dataGridView1.Columns.Count);


        for (int j = 0; j < dataGridView1.Columns.Count; j++)
        {
            table.AddCell(new Phrase(datagridview[j, 0].Value.ToString(), font));
        }

        table.HeaderRows = 1;

        for (int i = 0; i < dataGridView1.Rows.Count; i++)
        {
            for (int j = 0; j < dataGridView1.Columns.Count; j++)
            {
                try
                {
                    table.AddCell(new Phrase(dataGridView1[j, i].Value.ToString(), font));
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message);
                    cc = true;
                }
            }
        }


        pdfDoc.NewPage();

        pdfDoc.Add(jpg);

        pdfDoc.Add(table);
        pdfDoc.Close();

        Process.Start(strFileName);

     }


}   
4

1 回答 1

0

这不是一个答案(还)。您的代码似乎是一个更大项目的一部分,并且有很多与特定问题无关的无关代码。诊断此类问题的第一步是删除所有不必要的内容,以便我们可以实际重现您的问题。下面是这样做的尝试。

该代码首先根据您告诉我们的内容创建一个示例环境。首先,它创建一些示例数据并将其添加到DataGridView. 然后它将现有图像加载到PictureBox. 然后它将这两个控件添加到新创建的Panel. 在这些步骤之后,它会创建一个 PDF,从 中获取图像,PictureBox从表格中获取数据并将所有这些添加到 PDF 中。有关详细信息,请参阅代码中的注释。当我运行此代码时,我会在我的 PDF 中得到一个表格和一个图像。

如果您运行此代码,请开始一个全新的项目 - 不要使用您现有的项目。我怎么强调都不过分。不要选择此代码的一部分来运行,开始一个新项目并将其用于您的代码,并且仅将其用于您的代码。如果这可行,那么希望您可以开始比较工作代码和非工作代码之间的差异。

此代码在 VS Express 2012 For Windows Desktop 中针对 iTextSharp 5.4.0 进行了测试。

using iTextSharp.text;
using iTextSharp.text.pdf;
using System;
using System.Collections.Generic;
using System.Drawing;
using System.IO;
using System.Windows.Forms;

namespace WindowsFormsApplication20 {
    public partial class Form1 : Form {
        public Form1() {
            InitializeComponent();
        }
        //Used for our sample data
        public class Person {
            public string FirstName { get; set; }
            public string LastName { get; set; }
        }

        private void Form1_Load(object sender, EventArgs e) {
            //Sample image, set to a PNG
            var sampleImagePath = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "sample.png");
            //Full path to the PDF to export
            var exportFilePath = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf");

            //Next we're going to create all of the basic controls per the OP's scenario

            //Create some sample data to put into our DGV
            var P1 = new Person() { FirstName = "Alice", LastName = "Cooper" };
            var P2 = new Person() { FirstName = "Bob", LastName = "Dole" };
            var People = new List<Person>(new Person[] { P1, P2 });

            //Create our sample DataGridView
            var dataGridView1 = new DataGridView();
            dataGridView1.AutoGenerateColumns = true;
            dataGridView1.DataSource = People;
            dataGridView1.Location = new Point(0, 0);

            //Create our sample PictureBox
            var PB = new PictureBox();
            PB.Load(sampleImagePath);
            PB.Location = new Point(400, 0);
            PB.SizeMode = PictureBoxSizeMode.AutoSize;


            //Create our sample panel and give it room to show everything
            var panel = new Panel();
            panel.AutoSize = true;
            panel.Dock = DockStyle.Fill;

            //Add the above controls to our DGV
            panel.Controls.Add(dataGridView1);
            panel.Controls.Add(PB);
            //Add the DGV to the form
            this.Controls.Add(panel);

            //Basic PDF creation here, nothing special
            using (var fs = new FileStream(exportFilePath, FileMode.Create, FileAccess.Write, FileShare.None)) {
                using (var pdfDoc = new Document(PageSize.A4)) {
                    using (var writer = PdfWriter.GetInstance(pdfDoc, fs)) {
                        pdfDoc.Open();

                        //Get our image (Code is mostly the OP's)
                        iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(PB.Image, System.Drawing.Imaging.ImageFormat.Png);
                        jpg.ScaleToFit(750, 850);
                        jpg.SetAbsolutePosition(0, 0);

                        //Create our table
                        var table = new PdfPTable(dataGridView1.Columns.Count);

                        //Add the headers from the DGV to the table
                        for (int j = 0; j < dataGridView1.Columns.Count; j++) {
                            table.AddCell(new Phrase(dataGridView1.Columns[j].HeaderText));
                        }

                        //Flag the first row as a header
                        table.HeaderRows = 1;

                        //Add the actual rows from the DGV to the table
                        for (int i = 0; i < dataGridView1.Rows.Count; i++) {
                            for (int j = 0; j < dataGridView1.Columns.Count; j++) {
                                table.AddCell(new Phrase(dataGridView1[j, i].Value.ToString()));
                            }
                        }

                        //Add our image
                        pdfDoc.Add(jpg);
                        //Add out table
                        pdfDoc.Add(table);
                        pdfDoc.Close();
                    }
                }
            }
        }
    }
}
于 2013-03-22T13:54:56.100 回答