Itext7 Сохранение полей таблицы, если таблица переходит на следующую страницу - PullRequest
0 голосов
/ 30 января 2020

Кто-нибудь может мне помочь, я пытаюсь создать PDF-файл, в котором есть таблица сотрудников, я получаю данные о сотрудниках из базы данных, чтобы таблица могла быть занята на одной или нескольких страницах документа.

Я установил поле таблицы

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

Но как только данные сотрудника генерируют еще одну страницу документа в формате pdf, поля теряются

Вот мой полный код как я создаю PDF и некоторые скриншоты

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

1 Ответ

0 голосов
/ 04 февраля 2020

Верхние и нижние поля не должны применяться к частям таблицы, разбитым на несколько страниц. Они определяют пространство только между предыдущим элементом и текущим (верхнее поле) и между текущим элементом и следующим (нижнее поле).

Если вы хотите сохранить интервал в верхней части таблицы, когда она разделяется на страницы, вы можете использовать функциональность верхнего и нижнего колонтитула. Верхние и нижние колонтитулы таблицы повторяются на каждой странице, занимаемой таблицей, и вы можете добавить ячейку без границ с фиксированной высотой, что приведет к интервалам на каждой странице. Вот пример:

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

Вот как выглядит результат:

result

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...