How to detect end of page in pdf using itextsharp

Hi I am using itextsharp to create a pdf file. I place the reverse image on it and I want this image to be on all pages. But when the first page is completed, the text will move to the next page automatically so that the image does not appear on a new page.

Is there a way to identify the end of the page so that we can add a new page, and then first set the image so that it appears in the background, and then you can add the remaining text.

All I want is for the image to be in the background on all pages of the PDF file.

+3
source share
3 answers

Just check the PdfWriter.PageNumber property as follows:

        using (FileStream fs = File.Create("test.pdf"))
        {
            Document document = new Document(PageSize.A4, 72, 72, 72, 72);
            PdfWriter writer = PdfWriter.GetInstance(document, fs);

            document.Open();
            int pageNumber = -1;

            for (int i = 0; i < 20; i++)
            {
                if (pageNumber != writer.PageNumber)
                {
                    // Add image
                    pageNumber = writer.PageNumber;
                }

                // Add something else
            }

            document.Close();
        }
+1
source

I suggest you use the page event:

myWriter.setPageEvent(new BackgroundPageEvent(backgroundImage));

class BackgroundPageEvent extends PdfPageEventHelper {
  Image backgroundImage = null;
  public BackgroundPageEvent( Image img ) {
    backgroundImage = img;
  }
  public void onStartPage(PdfWriter writer, Document doc) {
    PdfContentByte underContent = writer.getDirectContentUnder();
    underContent.addImage(backgroundImage);
  }
}

With the above code backgroundImagewill be added to the "under the content" when creating each page. No need to worry about when to add it yourself ... iText will consider this for you, and the first thing in underContent of each page will be your image. You may need to play around with various addImage overrides to get the right size.

, doc , . , , , / (, , ).


PdfPageEvent , . PdfPageEventHelper "no ops", [s], :

  • OnStartPage
  • OnEndPage
  • OnCloseDocument
  • OnParagraph
  • OnParagraphEnd
  • OnChapter
  • OnChapterEnd
  • OnSection
  • OnSectionEnd
  • OnGenericTag

Handy. () , , OnGenericTag rect, , . .

+3

Please demonstrate how to use this?

0
source

Source: https://habr.com/ru/post/1782270/


All Articles