Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 使用itextsharp合并各种组件以在c中创建pdf#_C#_Itextsharp - Fatal编程技术网

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

C# 使用itextsharp合并各种组件以在c中创建pdf#,c#,itextsharp,C#,Itextsharp,我有一个c#面板,其中包含各种组件,如图片框和datagridview。 我希望创建一个pdf,其中包括整个datagridview和图片框。 目前,pdf中只显示datagridview或图片框。将两者合并在一起是不可能的。我正在使用iTextSharp创建pdf。 我的代码如下 string strFileName; string FontPath = "C:\\WINDOWS\\Fonts\\simsun.ttc,1"; int Font

我有一个c#面板,其中包含各种组件,如图片框和datagridview。 我希望创建一个pdf,其中包括整个datagridview和图片框。 目前,pdf中只显示datagridview或图片框。将两者合并在一起是不可能的。我正在使用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);

     }


}   
字符串strFileName;
string FontPath=“C:\\WINDOWS\\font\\simsun.ttc,1”;
int FontSize=12;
///
布尔cc=假;
SaveFileDialog savFile=新建SaveFileDialog();
savFile.AddExtension=true;
savFile.DefaultExt=“pdf”;
savFile.Filter=“PDF文档|*.PDF |*.PDF |”;
savFile.ShowDialog();
如果(savFile.FileName!=“”)
{
strFileName=savFile.FileName;
}
其他的
{
MessageBox.Show(“导出停止”、“导出停止”、MessageBoxButtons.OK、MessageBoxIcon.Information);
返回;
}
iTextSharp.text.Image jpg=iTextSharp.text.Image.GetInstance(Properties.Resources.template3,System.Drawing.Imaging.ImageFormat.Png);
jpg.ScaleToFit(750850);
jpg.SetAbsolutePosition(0,0);
//页面站点和页边距定义为左、右、上、下
文档pdfDoc=新文档(PageSize.A4);/,10f、10f、10f、0f);
//如果要选择图像作为背景,
PdfWriter writer=PdfWriter.GetInstance(pdfDoc,newfilestream(strFileName,FileMode.Create));
BaseFont BaseFont=BaseFont.CreateFont(FontPath、BaseFont.IDENTITY、BaseFont.NOT_EMBEDDED);
iTextSharp.text.Font Font=新的iTextSharp.text.Font(baseFont,FontSize);
pdfDoc.Open();
PdfPTable table=新的PdfPTable(dataGridView1.Columns.Count);
对于(int j=0;j
这还不是答案。您的代码似乎是一个更大项目的一部分,并且有许多与特定问题无关的无关代码。诊断这类问题的第一步是删除所有不必要的内容,这样我们就可以重现您的问题。下面是一个这样做的尝试

代码首先根据您告诉我们的内容创建一个示例环境。首先,它创建一些示例数据并将其添加到
DataGridView
中。然后它将现有图像加载到
图片盒中。然后将这两个控件添加到新创建的
面板中。完成这些步骤后,它将创建一个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();
                    }
                }
            }
        }
    }
}
使用iTextSharp.text;
使用iTextSharp.text.pdf;
使用制度;
使用System.Collections.Generic;
使用系统图;
使用System.IO;
使用System.Windows.Forms;
命名空间Windows窗体应用程序20{
公共部分类Form1:Form{
公共表格1(){
初始化组件();
}
//用于我们的样本数据
公共阶层人士{
公共字符串名{get;set;}
公共字符串LastName{get;set;}
}
私有void Form1\u加载(对象发送方、事件参数e){
//示例图像,设置为PNG
var sampleImagePath=Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),“sample.png”);
//要导出的PDF的完整路径
var exportFilePath=System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop),“Test.pdf”);
//接下来,我们将根据OP的场景创建所有基本控件
//创建一些示例数据以放入DGV
var P1=newperson(){FirstName=“Alice”,LastName=“Cooper”};
var P2=newperson(){FirstName=“Bob”,LastName=“Dole”};
var People=新列表(新人员[]{P1,P2});
//创建示例DataGridView
var dataGridView1=新的DataGridView();
dataGridView1.AutoGenerateColumns=true;
dataGridView1.DataSource=人;
dataGridView1.Location=新点(0,0);
//创建我们的示例PictureBox
var PB=新的PictureBox();
PB.载荷(采样图像路径);
PB.位置=新点(400,0);
PB.SizeMode=PictureBoxSizeMode.AutoSize;
//创建我们的样本面板,并给它展示一切的空间
变量面板=新面板();
panel.AutoSize=true;
panel.Dock=DockStyle.Fill;
//将上述控件添加到DGV