// step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(new File(directory, name + filename)));
// step 3: we open the document
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfImportedPage page = writer.getImportedPage(reader, pagenumber);
int rotation = reader.getPageRotation(pagenumber);
if (rotation == 90 || rotation == 270) {
cb.addTemplate(page, 0, -1f, 1f, 0, 0, reader.getPageSizeWithRotation(pagenumber).height());
}
else {