Skip to content

PDFDocument: How to Add New Content to a Given Page

When creating a PDF it is not always possible to anticipate how many pages the document will have. And yet, that is necessary, for example, to add a footer reflecting the current page number over the total of pages in the document. So how do you add this new content to your PDFs?

The solution is to use the PageCount and CurrentPage properties in Xojo’s PDFDocument class. The PageCount property gives the total number of pages in the PDF, and the the CurrentPage property (read/write) can be used to reach a given page within a PDF being created. This way, when we assign a new value to the CurrentPage property, it will retrieve the current Graphics context for that page in order to continue adding new content.

Let’s see how this works through this example. Let’s create a 10 page PDF and then add the numbered footer on every page of the document:

Var d As New PDFDocument
Var g As Graphics = d.Graphics

// Adding a total of 10 pages to the PDF
For n As Integer = 1 To 9
  g.DrawText("Some sample text in page #" + n.ToString, 20, 20)
  g.NextPage
Next n

// Once we create the pages with some content on them,
// we iterate on every page in order to add the footer.
// Remember that the first page in a PDF document starts at 1!
Var x As Integer = d.PageCount
For i As Integer = 1 To x

// Here is where we set which will be the current "active" page;
// that is, the one retrieving the current Graphics context.
d.CurrentPage = i
g.DrawText("Page " + i.ToString + " of " + x.ToString, 20, g.Height - 30)
Next i

// Lastly, we save our PDF to a FolderItem.
d.Save(SpecialFolder.Desktop.Child("CurrentPage.PDF"))

Run this sample snippet of code and you’ll get a PDF on your computer Desktop. Open it using your preferred PDF viewer app and you’ll see how the second loop was able to draw again on every one of the pages from the PDF we created.

Javier Menendez is an engineer at Xojo and has been using Xojo since 1998. He lives in Castellón, Spain and hosts regular Xojo hangouts en español. Ask Javier questions on Twitter at @XojoES or on the Xojo Forum.