Search code examples
c#itextitext7

SetNextRenderer Doesn't Trigger Draw Method For Renderer In IText7


I have a custom AreaBreak renderer shown in below :

 protected internal class CustomAreaBreakRenderer: AreaBreakRenderer
 {
      public Document document { get; set; }      
      public CustomAreaBreakRenderer(AreaBreak areaBreak, Document document) : base(areaBreak)
      {
          this.document = document;  
      }

      public override IRenderer GetNextRenderer()
      {
          document.Add(TableFactory.CreateLogoBlock());
          return new CustomAreaBreakRenderer(areaBreak, document);
      }
    
      public override void Draw(DrawContext drawContext)
      {
          base.Draw(drawContext); 
          document.Add(TableFactory.CreateContentBlock());
      }
 }

And I have set this renderer as :

var areaBreak = new AreaBreak();
var renderer  = new CustomAreaBreakRenderer(areaBreak, document);
areaBreak.SetNextRenderer(renderer);
document.Add(areaBreak);

When I debug my code,

GetNextRenderer() method is triggering but Draw() is not triggering.

I have used another renderers such as CustomTableRenderers or CustomParagraphRenderers and I always used the same approach but for this one, I cant use the renderer as expected..

Please help.. :)

NOTE: I tried TableRenderer and it worked, this seems only happening in AreaBreakRenderer!


Solution

  • The AreaBreakRenderer is not supposed to be drawn, its layout method always returns NOTHING.

    If you want to catch the event of going to the next page and draw something when that happens, you should customize your DocumentRenderer instead. Here is an example:

    private static class CustomDocumentRenderer extends DocumentRenderer {
        public CustomDocumentRenderer(Document document) {
            super(document);
        }
    
        @Override
        protected LayoutArea updateCurrentArea(LayoutResult overflowResult) {
            LayoutArea prevArea = currentArea != null ? currentArea.clone() : null;
            LayoutArea newArea = super.updateCurrentArea(overflowResult);
            if (prevArea == null || prevArea.getPageNumber() != newArea.getPageNumber()) {
                document.add(new Paragraph("Hello"));
            }
            return newArea;
        }
    }
    

    Plugging that custom renderer in is easy:

    Document doc = new Document(pdfDoc);
    
    doc.setRenderer(new CustomDocumentRenderer(doc));