New content can be added to a document in several different ways. New pages can be added to existing documents and new Page Elements can be added to any imported page or page in an imported PDF document.
New pages can be added to the beginning or end of an imported PDF document,as well as being inserted to the middle of the PDF document. Page Elements from DynamicPDF Generator for Java can then be placed on these pages. It is also possible to add existing pages from a separate PDF document using the ImportedPage class.
The following code shows how to add a cover page to a PDF document.
[Java]
MergeDocument document = new MergeDocument("[PhysicalPath]/DocumentA.pdf");
Page page = new Page(PageSize.LETTER, PageOrientation.PORTRAIT);
page.getElements().add(new Label("Cover Page", 0, 0, 512, 12));
document.getPages().add(0, page);
document.draw("[PhysicalPath]/MyDocument.pdf");
New content can be added to any imported page from an existing PDF document. This is accomplished by adding Page Elements from DynamicPDF Generator for Java to the imported page's getElements() collection.
The following code shows how to adds new content to an existing page in a PDF document.
[Java]
MergeDocument document = new MergeDocument("[PhysicalPath]/DocumentA.pdf");
Page page = document.getPages().getPage(0);
page.getElements().add(new Label("New Content", 0, 0, 512, 12));
document.getPages().add(0, page);
document.draw("[PhysicalPath]/MyDocument.pdf");
Page elements can be added beneath the content of the imported page by adding page elements to the imported page's getBackgroundElements() collection.
The following code will import a page and add a background to it.
[Java]
Document document = new Document();
ImportedPage page = new ImportedPage("[PhysicalPath]/DocumentA.pdf", 1);
page.getBackgroundElements().add(new Image("[PhysicalPath]/BackgroundImage.png", 200, 200, 1));
page.getBackgroundElements().add(new Label("Label Text2", 100, 120, 100, 12));
document.getPages().add(page);
document.draw("[PhysicalPath]/MyDocument.pdf");
Note: The examples in this topic show how to import documents and pages that are not going to be reused multiple times. For details on how to most efficiently handle documents and pages that will be used multiple times, see the Performance Considerations topic.