Search code examples
javaitext7

Different Leading for each page in itext 7


How i can set different fixedLending on specific page page ? How i can specific page when i add a paragraph?

 String line = "Hello! Welcome to iTextPdf";
    Div div = new Div();
        for (int i = 0; i < 30; i++) {
            Paragraph element = new Paragraph();
            element.add(line + " " + i);
      

            paragraphs.add(element);

        }

  
--------------
      if(page==1) // This is just for an example. How I want it to be
       element.setFixedLeading(100);
       else if(page==3)
     element.setFixedLeading(50);

After adding paragraphs, I need to do different setFixedLeading for the first and third page


Solution

  • You need a custom renderer for it - the renderer knows the context in which the element is going to be placed. Here is example code:

    private static class VariableLeadingParagraphRenderer extends ParagraphRenderer {
        public VariableLeadingParagraphRenderer(Paragraph modelElement) {
            super(modelElement);
        }
    
        @Override
        public LayoutResult layout(LayoutContext layoutContext) {
            setLeadingBasedOnPageNumber(layoutContext.getArea().getPageNumber());
            return super.layout(layoutContext);
        }
    
        private void setLeadingBasedOnPageNumber(int pageNumber) {
            if (pageNumber == 1) {
                this.setProperty(Property.LEADING, new Leading(Leading.FIXED, 100));
            } else {
                this.setProperty(Property.LEADING, new Leading(Leading.FIXED, 50));
            }
        }
    
        @Override
        public IRenderer getNextRenderer() {
            return new ParagraphRenderer((Paragraph) modelElement);
        }
    }
    

    Note that the logic of determining the desired leading depending on the page number resides in VariableLeadingParagraphRenderer#setLeadingBasedOnPageNumber

    You can then use the custom renderer as follows:

    Document document = new Document(pdfDocument);
    
    String line = "Hello! Welcome to iTextPdf";
    for (int i = 0; i < 30; i++) {
        Paragraph element = new Paragraph();
        element.add(line + " " + i);
        element.setNextRenderer(new VariableLeadingParagraphRenderer(element));
        document.add(element);
    }
    
    

    Visual result. Page 1:

    page 1

    Page 2:

    page 2