Hi,
Hi Saurabh,
Thanks for your inquiry. Please check the following code snippet to add a text/image stamp in the center of a PDF page while creating a new PDF document and setting page margins (border) as well. Hopefully, it will help you to accomplish the task.
Please note that, as the PDF document is created dynamically by API and in order to obtain real PDF document pages, we need to render its programming/dynamic model. Thus we can render the PDF document model by calling the save()
method or processParagraphs()
and later can iterate through the pages to add stamps.
Furthermore, to add a stamp on some specific position, you need to set the stamp XIndent
and YIndent
properties accordingly.
Document pdf = new Document();
Page page = pdf.getPages().add();
// Set page margins
MarginInfo margin = page.getPageInfo().getMargin();
margin.setLeft(10);
margin.setRight(10);
margin.setTop(10);
margin.setBottom(10);
TextFragment text = new TextFragment("Aspose.Pdf for Java");
// Add text fragments to the page
for (int i = 0; i < 400; i++) {
page.getParagraphs().add(text);
}
// Render PDF document structure
pdf.processParagraphs();
// Image stamp
ImageStamp imageStamp = new ImageStamp(myDir + "aspose_pdf-for-java.jpg");
imageStamp.setHorizontalAlignment(HorizontalAlignment.Center);
imageStamp.setVerticalAlignment(VerticalAlignment.Center);
imageStamp.setBackground(true);
// Text stamp
TextStamp textStamp = new TextStamp("Hello World");
textStamp.setTextAlignment(HorizontalAlignment.Center);
textStamp.setBackground(false);
textStamp.setOpacity(0.5);
textStamp.setRotateAngle(0);
textStamp.setHorizontalAlignment(HorizontalAlignment.Center);
textStamp.setVerticalAlignment(VerticalAlignment.Center);
// Add stamps to all pages
for (int i = 1; i <= pdf.getPages().size(); i++) {
pdf.getPages().get_Item(i).addStamp(textStamp);
pdf.getPages().get_Item(i).addStamp(imageStamp);
}
// Save the output PDF
pdf.save(myDir + "test_stampout.pdf");
Please feel free to contact us for any further assistance.
Best Regards,
Hello ,
Hi Saurabh,
Hi,
Hi Saurabh,