将datagridview中的选定行复制到Pdf

时间:2016-12-05 08:24:25

标签: c# pdf datagridview itext

我正在尝试使用mouseclick将数据网格视图中的选定行复制到pdf中。代码正在运行,但它复制了所有行,而不仅仅是我选择的行。

代码:

private void dataGridView1_MouseDoubleClick(object sender, MouseEventArgs e)
{
    Document doc = new Document(iTextSharp.text.PageSize.LETTER, 10, 10, 42, 35);
    PdfWriter wri = PdfWriter.GetInstance(doc, new FileStream(@"C:\Users\navee\Desktop\Leihvertrag.pdf", FileMode.Create, FileAccess.ReadWrite));
    doc.Open();

    iTextSharp.text.Image Diamant = iTextSharp.text.Image.GetInstance(@"C:\Users\navee\Desktop\DiamantPDF.PNG");
    Diamant.ScalePercent(72f);
    doc.Add(Diamant);
    Paragraph paragraph = new Paragraph("            \n ________________________________________________________________________________________         \n                                                                      PFANDLEIHHAUS WVB \n                                                                               - Leihvertrag - \n ________________________________________________________________________________________ \n \n \n");
    Paragraph anschrift = new Paragraph("        WVB\n        def \n        11111 abc\n        Tel.0000/0000");
    Paragraph leerzeichen = new Paragraph("\n \n \n \n \n \n \n \n \n               _______________________                                                     _______________________");
    Paragraph unterschrift = new Paragraph("                      Unterschrift Pfänder                                                                     Unterschrift Kunde ");

    Paragraph agbs = new Paragraph("\n \n \n AGB: Der Vertrag ist nicht Widerrufbar ! \n \n Leihgebühr : 1 Monat = 5 €\n                      2 Monate = 10 € \n                      3 Monate  = 15 €");

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

    foreach (DataGridViewRow row in dataGridView1.SelectedRows)
    {            
        for (int j = 0; j < dataGridView1.Columns.Count; j++)
        {
            table.AddCell(new Phrase(dataGridView1.Columns[j].HeaderText));
        }

        table.HeaderRows = 1;

        for (int i = 0; i < dataGridView1.Rows.Count; i++)
        {
            for (int k = 0; k < dataGridView1.Columns.Count; k++)
            {
                if (dataGridView1[k,i].Value != null)
                {
                    table.AddCell(new Phrase(dataGridView1[k, i].Value.ToString()));
                } 
            }
        }
        doc.Add(anschrift);
        doc.Add(paragraph);
        doc.Add(table);
        doc.Add(leerzeichen);
        doc.Add(unterschrift);
        doc.Add(agbs);            

        doc.Close();
        System.Diagnostics.Process.Start(@"C:\Users\navee\Desktop\Leihvertrag.pdf");
    }
}

0 个答案:

没有答案