24

I'm trying to create a PDF Document using iText 7 with below code and my PDF documents contents are overlapping in same page when generated.(i.e in Page 1).

I see the

document.newPage();

method is missing in iText 7. How can i add pages to my PDF document without using pdfDocumet.copyPages(...) or PDFmerger in itext 7.

        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));      
        pdfDoc.addNewPage();
        Document PageOnedocument = new Document(pdfDoc,PageSize.A4);            
        addPageOneContents(PageOnedocument);  


        pdfDoc.addNewPage();
        Document PageTwodocument = new Document(pdfDoc,PageSize.A4);            
        addPageTwoContents(PageTwodocument);  

        pdfDoc.close();
        PageOnedocument.close();
        PageTwodocument.close();
Amedee Van Gasse
  • 7,280
  • 5
  • 55
  • 101
Karthick Radhakrishnan
  • 1,151
  • 3
  • 12
  • 32

2 Answers2

52

In iText 7 the newPage method has become a special case of an area break:

Document document = ...;
[....add some content...]
document.add(new AreaBreak(AreaBreakType.NEXT_PAGE));
[...add some content on next page...]
mkl
  • 90,588
  • 15
  • 125
  • 265
  • Is this documented somewhere? – AllirionX Jan 17 '20 at 04:55
  • 1
    @AllirionX In https://itextpdf.com/en/resources/books/itext-7-building-blocks/chapter-2-adding-content-canvas-or-document - but it is a bit hidden among more complex `AreaBreak` usages. – mkl Jan 17 '20 at 09:10
  • Thanks! It's very useful, I was getting mad trying to add a simple paragraph to a new page. – AllirionX Jan 17 '20 at 09:12
  • @mkl getting "Access denied" on trying to access that link. Is that only for commercial access? – Alex P. Mar 25 '23 at 18:52
  • 1
    @AlexP. *"Is that only for commercial access?"* - No, the book merely moved to a different URL, see https://kb.itextpdf.com/home/it7kb/ebooks/itext-7-building-blocks/chapter-2-adding-content-to-a-canvas-or-a-document - marketing likes to re-structure the site... – mkl Mar 28 '23 at 07:10
0

If you're using C# and refactoring code that referenced iText 5 (like I was) try putting the iText 7 method in an override.

public static class Itext7DocumentExtensions
{
    public static void NewPage(this Document document)
    {
        document.Add(new AreaBreak(AreaBreakType.NEXT_PAGE));
    }
}

Now you can call document.NewPage();

thefastlane
  • 29
  • 1
  • 8