0

I've a problem, i want to add an header and a footer into me pdf document. For that, i used to PdfPageEventHelper.

i've created a class :

    public class PDFFooter : PdfPageEventHelper
    {
        // write on top of document
        public override void OnOpenDocument(PdfWriter writer, Document document)
        {
            base.OnOpenDocument(writer, document);
        }

        // write on start of each page
        public override void OnStartPage(PdfWriter writer, Document document)
        {
            base.OnStartPage(writer, document);
            EnTeteDePage(document);
        }

        // write on end of each page
        public override void OnEndPage(PdfWriter writer, Document document)
        {
            base.OnEndPage(writer, document);
            PiedDePage(document);
        }

        //write on close of document
        public override void OnCloseDocument(PdfWriter writer, Document document)
        {
            base.OnCloseDocument(writer, document);
        }

        private void EnTeteDePage(Document document)
        {
            Controleur.ControleurParametre CP = new ControleurParametre();
            T_PARAMETRE _param = CP.Charger();
            T_ADRESSE _adresseParam = CP.ChargerAdresse(_param.ID_ADRESSE_SOCIETE);
            iTextSharp.text.Image img = (_param.PATH_LOGO_SOCIETE != "" && _param.PATH_LOGO_SOCIETE != null) ? iTextSharp.text.Image.GetInstance(_param.PATH_LOGO_SOCIETE) : null;
            if (img != null)
            {
                if (img.Width / 150 > img.Height / 150) img.ScalePercent((img.Width / 150) * 100);
                else img.ScalePercent((img.Height / 150) * 100);
                document.Add(img);
            }
            PdfPTable head = new PdfPTable(6);
            PdfPCell cell1 = new PdfPCell(img);
            PdfPCell cell2 = new PdfPCell(new Phrase("Rapport de réception de chantier \n" + _param.NOM_SOCIETE + " - " +
                _adresseParam.ADDR_VOIE + " - " +
                _adresseParam.ADDR_VOIE_BIS + "\n" +
                _adresseParam.ADDR_CP + " - " +
                _adresseParam.ADDR_VILLE + "\n"));
            float[] wid = new float[] { 0.1f, 0.9f };
            head.SetWidths(wid);
            cell1.HorizontalAlignment = 1;
            cell2.HorizontalAlignment = 1;
            head.AddCell(cell1);
            head.AddCell(cell2);
            document.Add(head);
        }
        private void PiedDePage(Document document)
        {
            Paragraph Footer = new Paragraph();

            document.Add(Footer);
        }
    }

i use a method to open my document :

    private async Task<bool> ouvrirPDF(iTextSharp.text.Rectangle re)
    {
        str = await f.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite);
        st = str.AsStreamForWrite();
        using (myDocument = new Document(re)) //Création du PDF
        {
            using (writer = PdfWriter.GetInstance(myDocument, st))
            {
                PDFFooter foot = new PDFFooter();
                writer.PageEvent = foot;
                myDocument.Open(); //Ouverture du PDF
                cb = writer.DirectContent;
            }
        }
        return true;
    }

But when i try to do myDocument.Open(), i have an exception "The document has no page"

Can you help me to resolve it ?

Moussawi
  • 393
  • 1
  • 6
  • 22
  • *when i try to do myDocument.Open(), i have an exception "The document has no page"* - I assume there is some other error during opening triggering the exit code of the `using (writer = PdfWriter.GetInstance(myDocument, st))` which tries to close the document and fails with that message because there indeed are no pages yet. In such situation you had better try and catch the exception on the line which fails and inspect that exception. The actual problem during opening might indeed be due to the issues Bruno pointed out. – mkl Sep 03 '14 at 11:46

1 Answers1

0

There are two serious errors in your code:

  1. If you read the documentation, you will learn that you never ever should add content in the OnStartPage() method.
  2. If you read the documentation, you will learn that the document should be used as a READ-ONLY object. If is forbidden to do document.Add(). Instead you should add your header and footer at absolute positions (using the direct content of the writer).

Please throw away your code and don't start anew until after you've read the documentation. For some examples, see http://tinyurl.com/itextsharpIIA2C05

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
  • i used iTextSharp to Open and modify a document, it's worked so why i can't use it to create an header and footer ? – Moussawi Sep 03 '14 at 10:14
  • That's a very strange question. It sounds like "why can't I eat soup with a fork?" or "why can't I watch TV on my radio?" When you want to open an *existing document* and *stamp a header and a footer* on it, you use `PdfReader` and `PdfStamper`, **NOT** `PdfWriter` and **NOT** `PdfPageEvents`. Have you read the documentation? http://manning.com/lowagie2/samplechapter6.pdf – Bruno Lowagie Sep 03 '14 at 10:17
  • I don't use an existing document. I create a new document pdf and i use PdfWriter to put data into it – Moussawi Sep 03 '14 at 10:25
  • If you don't use an existing document, then why did you write "i used iTextSharp to Open and **modify** a document"? Modifying implies that there was already a document. Also: why do you say "it's worked" in your comment, but saying "Can you help me to resolve it?" in your question. Obviously something doesn't work, but you're very unclear about it and apparently unwilling to listen to advice. – Bruno Lowagie Sep 03 '14 at 10:28
  • it's worked without PdfPageEventHelper but for apply an header and a footer to all pages of my pdf document i must used it – Moussawi Sep 03 '14 at 10:34
  • You must use it **CORRECTLY** as documented in the book and in the examples. In my answer, I explained the **two major errors in your code** that cause your problem. If you don't believe me or choose to ignore my advice, so be it. After all, I'm the original author of iText, what do I know about using page events correctly? – Bruno Lowagie Sep 03 '14 at 11:50
  • Ok but how can i know when there is a new page in my document ? – Moussawi Sep 03 '14 at 12:22
  • Use page events, but use them correctly. That is: **do not use OnStartPage()** and **do not use document.add() inside your OnEndPage**! Read the examples that are provided in the documentation before writing your own code. – Bruno Lowagie Sep 03 '14 at 12:25
  • So if i anderstand, i can't put an event on my PdfWriter ? – Moussawi Sep 03 '14 at 12:41
  • You absolutely can put an event on your `PdfWriter`, you just can't talk to the `Document` directly. What if you your `Document.Add()` forced content on to a new page? Your `OnEndPage()` event could actually create an infinite loop. See [this for how to work with content in the header and footer](http://stackoverflow.com/a/15950145/231316). – Chris Haas Sep 03 '14 at 13:05
  • Thank you very much, i've found my problem ;) In event i use a PdfContentByte object and not directly a document object – Moussawi Sep 03 '14 at 13:11
  • That's indeed what I tried explaining in my answer by referring to the examples. – Bruno Lowagie Sep 03 '14 at 14:37