Warm tip: This article is reproduced from stackoverflow.com, please click
c# itext7

Itext7 Saving table margins if the table goes to the next page

发布于 2020-04-21 10:27:47

Can anybody give me a hand, i am traying to create a pdf file who has a table of employees inside, i get the employee data form a database, so the table could be occupied one o serveral pages of the document.

I set the margin of the table

table.SetMarginTop(100);
table.SetMarginBottom(20);

But as soon the employee data generates another page of the pdf documetn the margins get lost

Here is my complete code of how i am generating the pdf and some screenshots

internal bool CreatePdfInspectorDelegates(string storeName, DateTimePicker date, string inspector, DataTable delegateStoreDT, DataTable delegateEmployeeDT)
{try
    {
        string auxPath = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
        auxPath = auxPath + @"\PDF\Creados\notifacionInspectorDelegados" + storeName + ".pdf";

        PdfWriter writer = new PdfWriter(auxPath);
        PageSize ps = PageSize.LETTER;
        PdfDocument pdf = new PdfDocument(writer);
        Document doc = new Document(pdf, ps);

        //Fuentes de texto
        PdfFont fontNormal = PdfFontFactory.CreateFont(StandardFonts.TIMES_ROMAN);
        PdfFont fontBold = PdfFontFactory.CreateFont(StandardFonts.TIMES_BOLD);

        //Datos
        string dateIn = String.Format("Fecha{0}", date.Value.ToString("dd/MM/yyyy"));
        string instpector = String.Format("{0}", date.Value.ToString("dd/MM/yyyy"));

        //Cuerpo
        Paragraph pTittel = new Paragraph();
        pTittel.SetPaddingTop(70);
        pTittel.SetFixedLeading(25);
        Text text = new Text("NOTIFICACIÓN AL INSPECTOR O INSPECTORA DEL TRABAJO\n DE LA VOLUNTAD DE LOS TRABAJADORES Y LAS TRABAJADORAS\n DE ELEGIR A LOS DELEGADOS Y A LAS DELEGADAS DE PREVENCIÓN").SetFont(fontBold).SetTextAlignment(TextAlignment.CENTER);
        pTittel.SetTextAlignment(TextAlignment.CENTER);
        pTittel.Add(text);

        Paragraph pBody = new Paragraph();
        pBody.SetFixedLeading(22);
        Text text2 = new Text("\nFecha: ").SetFont(fontNormal);
        Text textDate = new Text(date.Value.ToString("dd/MM/yyyy")).SetFont(fontNormal).SetUnderline();
        Text text3 = new Text("\n\nCiudadano(a):\n").SetFont(fontNormal);
        Text textInspector = new Text(inspector).SetFont(fontNormal).SetUnderline();
        Text text4= new Text("\n\nNosotros, los(as) trabajadores(as), en cumplimiento a lo señalado en el artículo 41 de la Ley Orgánica de Prevención, Condiciones y Medio Ambiente de Trabajo(Lopcymat) y del artículo 58 de su Reglamento Parcial, nos dirigimos a Usted con el objeto de manifestarle nuestra voluntad de elegir a los Delegados y / o Delegadas de Prevención correspondientes a la entidad de trabajo: ").SetFont(fontNormal);
        Text textCenter = new Text("GRUPO TOTAL 99 C.A.").SetFont(fontBold).SetUnderline();
        Text text5 = new Text(" cuya dirección es: ").SetFont(fontNormal);
        Text textCenterAddress = new Text("CALLE LAS VEGAS CRUCE CON SOLEDAD EDIFICIO CLARIANT VENEZUELA, ZONA INDUSTRIAL DE LA TRINIDAD, CARACAS. ").SetFont(fontNormal).SetUnderline();
        Text text6 = new Text(" , específicamente los correspondientes al centro de trabajo: ").SetFont(fontNormal);
        Text textBranch = new Text(GetStoreBranch(delegateStoreDT).ToUpper()).SetFont(fontNormal).SetUnderline();
        Text text7 = new Text(" , ubicado en: ").SetFont(fontNormal);
        Text textBranchAddress = new Text(GetStoreAddress1(delegateStoreDT).ToUpper() + ", " + GetStoreAddress2(delegateStoreDT).ToUpper()).SetFont(fontNormal).SetUnderline();
        Text text8 = new Text("\n\nNotificación que se hace para efectos del artículo 59 del Reglamento Parcial de la Ley Orgánica de Prevención, Condiciones y Medio Ambiente de Trabajo(RLopcymat).\n\nA continuación firman los(as) trabajadores(as) solicitantes:\n").SetFont(fontNormal);

        pBody.Add(text2);
        pBody.Add(textDate);
        pBody.Add(text3);
        pBody.Add(textInspector);
        pBody.Add(text4);
        pBody.Add(textCenter);
        pBody.Add(text5);
        pBody.Add(textCenterAddress);
        pBody.Add(text6);
        pBody.Add(textBranch);
        pBody.Add(text7);
        pBody.Add(textBranchAddress);
        pBody.Add(text8);

        pBody.SetTextAlignment(TextAlignment.JUSTIFIED);

        doc.Add(pTittel);
        doc.Add(pBody);

        //Segunda pagina
        doc.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));

        //Empleados
        float[] columnWidths = { 5, 5, 5, 5, 4 };
        Table table = new Table(UnitValue.CreatePercentArray(columnWidths));
        table.SetWidth(UnitValue.CreatePercentValue(100));


        Cell[] header =
        {
        new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Nombres y Apeliidos").SetTextAlignment(TextAlignment.CENTER).SetBold()),
        new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Cedula\nIdentidad N°").SetTextAlignment(TextAlignment.CENTER).SetBold()),
        new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Cargo Actual").SetTextAlignment(TextAlignment.CENTER).SetBold()),
        new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Firma").SetTextAlignment(TextAlignment.CENTER).SetBold()),
        new Cell().SetBackgroundColor(new DeviceGray(0.75f)).Add(new Paragraph("Huella").SetTextAlignment(TextAlignment.CENTER).SetBold())
        };

        foreach (Cell cells in header)
        {
            table.AddCell(cells);
        }


        foreach (DataRow row in delegateEmployeeDT.Rows)
        {
            if (row[0].ToString() == "True")
            {
                table.AddCell(new Cell().SetMinHeight(80).SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph(row[2].ToString().ToUpper() + "\n" + row[3].ToString().ToUpper()).SetTextAlignment(TextAlignment.CENTER)));
                table.AddCell(new Cell().SetMinHeight(80).SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph(row[4].ToString().ToUpper()).SetTextAlignment(TextAlignment.CENTER)));
                table.AddCell(new Cell().SetMinHeight(80).SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph(row[5].ToString().ToUpper()).SetTextAlignment(TextAlignment.CENTER)));
                table.AddCell(new Cell().SetMinHeight(80).SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph("")));
                table.AddCell(new Cell().SetMinHeight(80).SetTextAlignment(TextAlignment.CENTER).Add(new Paragraph("")));               
            }
        }

        table.SetMarginTop(100);
        table.SetMarginBottom(20);
        doc.Add(table);
        doc.Close();
        return true;
    }
    catch (Exception e)
    {
        return false;
    }
}

Margin Lost

With Margin

Questioner
Edgar Gomez
Viewed
46
Alexey Subach 2020-02-04 14:19

Top and bottom margins are not supposed to be applied to parts of the table that breaks across several pages. They only define space between previous element and current one (top margin) and between current element and next one (bottom margin).

If you want to preserve spacing on top of a table when it splits across pages you can use header and footer functionality. Table headers and footers are repeated on each page occupied by a table, and you can add a cell without borders with fixed height which will result in spacing on each page. Here is an example:

PdfDocument pdfDoc = new PdfDocument(new PdfWriter(outFileName));
Document doc = new Document(pdfDoc, PageSize.A4.rotate());

doc.add(new Paragraph("Starting text"));

Table table = new Table(UnitValue.createPercentArray(5)).useAllAvailableWidth();
table.addHeaderCell(new Cell(1, 5).setHeight(100).setBorder(Border.NO_BORDER));
table.addHeaderCell(new Cell(1, 5).
        add(new Paragraph("Header")));
table.addFooterCell(new Cell(1, 5).
        add(new Paragraph("Footer")));
table.addFooterCell(new Cell(1, 5).setHeight(100).setBorder(Border.NO_BORDER));
for (int i = 0; i < 350; i++) {
    table.addCell(new Cell().add(new Paragraph(String.valueOf(i + 1))));
}

doc.add(table);
doc.close();

Here is what the result looks like:

result