使用itextsharp合并各种组件以在c#中创建pdf

时间:2013-03-22 06:04:47

标签: c# itextsharp

我在c#中有一个面板,其中包含各种组件,如图片框和数据网格视图。 我希望创建一个pdf,其中包括整个datagridview和图片框。 目前,只有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);

     }


}   

1 个答案:

答案 0 :(得分:0)

这还不是答案。您的代码似乎是较大项目的一部分,并且存在许多与特定问题无关的无关代码。诊断这样的事情的第一步是删除所有不必要的东西,以便我们可以实际重现您的问题。以下是尝试这样做。

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

如果您运行此代码,开始一个全新的项目 - 请勿使用您现有的项目。我不能强调这一点。不要选择运行此代码的部分内容,启动一个新项目并使用此代码,并将其用于代码。如果这样可行,那么希望您可以开始比较工作代码和非工作代码之间的差异。

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

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