Corrected code for page number in pdf

This commit is contained in:
nisha
2024-10-13 04:39:24 +05:30
parent f0d1af1842
commit 7fd5a4cb27
2 changed files with 79 additions and 15 deletions

View File

@@ -0,0 +1,45 @@
package net.gepafin.tendermanagement.dao;
import com.itextpdf.text.BaseColor;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.FontFactory;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfStamper;
import com.itextpdf.text.pdf.PdfContentByte;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
public class PdfPageNumberInserter {
public static byte[] addPageNumbers(byte[] pdfData) throws IOException, DocumentException {
PdfReader reader = new PdfReader(pdfData); // Read the generated PDF
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
BaseColor darkGreenColor = new BaseColor(1, 50, 32); // Adjust RGB values as needed
Font baseFont = FontFactory.getFont(FontFactory.HELVETICA, 4,darkGreenColor);
BaseFont font = baseFont.getBaseFont();
// PdfStamper allows us to modify the existing PDF
PdfStamper stamper = new PdfStamper(reader, outputStream);
int totalPages = reader.getNumberOfPages();
// Set the font for page numbers
for (int i = 1; i <= totalPages; i++) {
// Get the content of the current page
PdfContentByte over = stamper.getOverContent(i);
over.beginText();
over.setFontAndSize(font, 12);
// Add the page number at the bottom center of the page
over.showTextAligned(PdfContentByte.ALIGN_CENTER, "Page " + i + " of " + totalPages, 300, 30, 0);
over.endText();
}
stamper.close();
reader.close();
return outputStream.toByteArray(); // Return the modified PDF with page numbers
}
}