I want to add an header to an existing pdf using iText.
I had no problem except that sometimes my function create a pdf with the correct header and footer but with the existing pdf page rotated.
private static void print(Sldocuments item, String header, String footer) {
try {
String ftpFilename = item.getId()+"_"+item.getDocumentname();
String newName= String.valueOf(item.getId())+".pdf";
String path = (Global.SHARED_FOLDER_DEVELOPER);
String smbUser = "**;"+"**" + ":" + "**";
NtlmPasswordAuthentication auth = new NtlmPasswordAuthentication(smbUser);
SmbFile sFile = new SmbFile(path+ftpFilename, auth);
InputStream in = sFile.getInputStream();
PdfReader reader = new PdfReader(in);
// Create output PDF
Document document = new Document(PageSize.A4);
SmbFile sFileOut = new SmbFile(path+newName, auth);
SmbFileOutputStream sfos = new SmbFileOutputStream(sFileOut);
PdfWriter writer = PdfWriter.getInstance(document, sfos);
document.open();
PdfContentByte pdfContentByte = writer.getDirectContent();
for (int i = 1; i <= reader.getNumberOfPages(); i++) {
PdfImportedPage page = writer.getImportedPage(reader, i);
document.newPage();
pdfContentByte.add(page);
// Write header
writeText(headerPositionX, headerPositionY, header);
// Write footer
writeText(footerPositionX, footerPositionY, footer);
// Write page number
String pageNumber = "pagina "+ i +" di " + reader.getNumberOfPages();
writeText(pageNumberPositionX, pageNumberPositionY, pageNumber);
}
document.close();
reader.close();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
I tried fix my problem using
AffineTransform af = new AffineTransform();
af.setToRotation(Math.toRadians(page.getRotation()));
pdfContentByte.addTemplate(page, af);
insthead of the simple
pdfContentByte.add(page);
but with this transformation, the imported page is totally missing from my new pdf (maybe cause I rotate the page using a wrong anchor point).
How can I achieve my goal?