iTextSharp 5: как выровнять номер страницы "x / x" справа от нижнего колонтитула - PullRequest
0 голосов
/ 09 марта 2019

Я новичок в iTextSharp 5 и хочу узнать, как мне выровнять номер страницы в этом формате CurrentPage / TotalPages справа от нижнего колонтитула.Когда я создаю нижний колонтитул с номерами страниц и некоторой информацией о них, мне удается написать CurrentPage / справа, а TotalPages слева.Это мой код.

public override void OnEndPage(PdfWriter writer, Document document)
    {


        double capitalsocial;
        CultureInfo culture;
        string specifier = "N";
        iTextSharp.text.Font pfontfooter = FontFactory.GetFont(iTextSharp.text.Font.FontFamily.UNDEFINED.ToString(), 9f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.BLACK);
        iTextSharp.text.Font pfontNumbrePage = FontFactory.GetFont(iTextSharp.text.Font.FontFamily.UNDEFINED.ToString(), 13f, iTextSharp.text.Font.NORMAL, iTextSharp.text.BaseColor.LIGHT_GRAY);

        base.OnEndPage(writer, document);
        var tableContainerFooter = new PdfPTable(new[] { 9F, 1f })
        {
            TotalWidth = 550f,
            PaddingTop = -51f,
            SpacingAfter = -50f,
            SpacingBefore = -50f,
            DefaultCell = { BorderWidth = 0}
        };

        var tableFooter = new PdfPTable(new[] { 9F })
        {
            DefaultCell = { BorderWidth = 0, HorizontalAlignment = 1},  //0=Left, 1=Centre, 2=Right
            TotalWidth = 500f,
            PaddingTop = -51f,
        };
        tableFooter.HorizontalAlignment = 1;
        tableFooter.DefaultCell.BorderWidth = 0;
        tableFooter.DefaultCell.HorizontalAlignment = 1;

        cb = writer.DirectContentUnder;
        PdfTemplate templateM = cb.CreateTemplate(50, 50);
        templates.Add(templateM);

        int pageN = writer.CurrentPageNumber;
        String pageText = pageN.ToString() + "/";
        BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);

        float len = bf.GetWidthPoint(pageText, 12);
        cb.BeginText();
        cb.SetFontAndSize(bf, 10);
        cb.SetTextMatrix(document.RightMargin + len + 530f, document.PageSize.GetBottom(document.BottomMargin));
        cb.ShowText(pageText);
        cb.EndText();
        cb.AddTemplate(templateM, document.RightMargin + len, document.PageSize.GetBottom(document.BottomMargin));

        tableFooter.AddCell(new Paragraph(new Chunk(new iTextSharp.text.pdf.draw.LineSeparator(-0.2F, 131F, BaseColor.LIGHT_GRAY, Element.ALIGN_CENTER, 9))));

        tableFooter.AddCell(new Paragraph(raison_sociale + " " + forme_juridique + " au capital de " + capital + "" + devise, pfontfooter));
        tableFooter.AddCell(new Paragraph("I.F: " + idfscal + " - R.C.: " + rc + " - Patente: " + patente + " - C.N.S.S: " + cnss + " - I.C.E: " + ice, pfontfooter));
        tableFooter.AddCell(new Paragraph("Tél.: " + tel1 + " - Fax: " + fax + " - Mail: " + email, pfontfooter));

        tableContainerFooter.AddCell(new PdfPCell(tableFooter) { BorderWidth = 0f, });

        tableContainerFooter.WriteSelectedRows(0, -1, 45f, document.Bottom + 55f, writer.DirectContent);

    }

    //write on close of document
    public override void OnCloseDocument(PdfWriter writer, Document document)
    {
        base.OnCloseDocument(writer, document);
        BaseFont bf = BaseFont.CreateFont(BaseFont.HELVETICA, BaseFont.CP1252, BaseFont.NOT_EMBEDDED);
        foreach (PdfTemplate item in templates)
        {
            item.BeginText();
            item.SetFontAndSize(bf, 10);

            item.SetTextMatrix(document.RightMargin, document.PageSize.GetBottom(document.BottomMargin));

            numberOfPages = writer.PageNumber;
            document.Add(new Paragraph("" + (writer.PageNumber)) { Alignment = Element.ALIGN_RIGHT, });
            item.EndText();
        }

    }

И вот как это выглядит

Это нижний колонтитул, который я сделал

1 Ответ

0 голосов
/ 09 марта 2019

Поскольку заранее узнать номер страницы невозможно, это можно сделать, создав pdf как двухэтапный процесс.

  1. Создание PDF без номеров страниц.
  2. Выполните рендеринг PDF еще раз, добавив число на каждой странице.

После того, как вы сгенерировали PDF, вызовите этот метод:

AddPageNo("Sushant_Without_pageNo.pdf","Sushant_With_pageNo.pdf");

Вы должны определить этот метод как:

void AddPageNo(string fileIn, string fileOut)
{
    byte[] bytes = File.ReadAllBytes(fileIn);
    Font blackFont = FontFactory.GetFont("Arial", 12, Font.NORMAL, BaseColor.BLACK);
    using (MemoryStream stream = new MemoryStream())
    {
        PdfReader reader = new PdfReader(bytes);
        using (PdfStamper stamper = new PdfStamper(reader, stream))
        {
            int pages = reader.NumberOfPages;
            for (int i = 1; i <= pages; i++)
            {
                ColumnText.ShowTextAligned(stamper.GetUnderContent(i), Element.ALIGN_RIGHT, new Phrase(i.ToString(), blackFont), 568f, 15f, 0);
            }
        }
        bytes = stream.ToArray();
    }
    File.WriteAllBytes(fileOut, bytes);
}
...