In order to add Header in PDF, we’ll use Aspose.PDF for Java API which is a feature-rich, powerful, and easy-to-use conversion API for the Java platform. You can download its latest version directly from Maven and install it within your Maven-based project by adding the following configurations to the pom.xml.
<repository>
<id>AsposeJavaAPI</id>
<name>Aspose Java AP</name>
<url>https://releases.aspose.com/java/repo/</url>
</repository>
<dependency>
<groupId>com.aspose</groupId>
<artifactId>aspose-pdf</artifactId>
<version>version of aspose-pdf API</version>
</dependency>
Add Header to PDF with Java
You need Aspose.PDF for Java to try the code in your environment.
- Open a PDF document using Document object.
- Create a Stamp and define its properties.
- Add the Stamp to Page using AddStamp method.
- Save the PDF file.
Add a Header to PDF Document - Java
// Open document
Document pdfDocument = new Document(dataDir+ "TextinHeader.pdf");
// Create header
TextStamp textStamp = new TextStamp("Header Text");
// Set properties of the stamp
textStamp.TopMargin = 10;
textStamp.HorizontalAlignment = HorizontalAlignment.Center;
textStamp.VerticalAlignment = VerticalAlignment.Top;
// Add header on all pages
foreach (Page page in pdfDocument.Pages)
{
page.AddStamp(textStamp);
}
// Save updated document
pdfDocument.Save(dataDir+ "TextinHeader_out.pdf");