I am having some issues with a PDF containing a rotation property created by a Xerox scanner. The below function was originally created to scale the height of an input PDF by the amount given by the variable scaleHeight. This works fine for input documents without rotation.
When testing a document with a 270 degree rotation, I found that the rotation property which would have made the document appear in a portrait orientation was ignored. Instead, the document appeared in a landscape orientation in the output PDF.
So I updated the function below to apply the scaling only when there is no rotation, and used another example I found online to try to fix the rotation.
This did not work, and resulted in a mirror image of the original document in portrait format.
So now I have two problems: 1. How to properly rotate the document contents. 2. How to scale the rotated contents.
If I can solve item 1, I can simply call the function again (with the rotation property removed) to fix item 2.
Thank you for any and all help, the function is below. The commented out lines referring to the rotationEvent did not help here either.
public String resizePDF (String pdfIn, float x, float y, float scaleHeight) throws Exception {
String pdfOut = pdfIn.substring(0, pdfIn.length() - 4) + "_resize.pdf";
PdfReader reader = new PdfReader(pdfIn);
int rotation = reader.getPageRotation(1);
com.itextpdf.text.Document doc = new com.itextpdf.text.Document(reader.getPageSizeWithRotation(1), 0, 0, 0, 0);
PdfWriter writer = PdfWriter.getInstance(doc, new FileOutputStream(pdfOut));
doc.open();
PdfContentByte cb = writer.getDirectContent();
Rotate rotationEvent = new Rotate();
writer.setPageEvent(rotationEvent);
for(int i=1; i<=reader.getNumberOfPages(); i++){
float pageWidth = reader.getPageSizeWithRotation(i).getWidth();
float pageHeight = reader.getPageSizeWithRotation(i).getHeight();
doc.newPage();
PdfImportedPage page = writer.getImportedPage(reader, i);
if (rotation == 0) {
cb.addTemplate(page, 1f, 0, 0, scaleHeight, x, y);
//rotationEvent.setRotation(PdfPage.PORTRAIT);
} else if (rotation == 90) {
cb.addTemplate(page, 0, -1f, 1f, 0, 0, pageHeight);
//rotationEvent.setRotation(PdfPage.LANDSCAPE);
} else if (rotation == 180) {
cb.addTemplate(page, 1f, 0, 0, -1f, pageWidth, pageHeight);
//rotationEvent.setRotation(PdfPage.INVERTEDPORTRAIT);
} else if (rotation == 270) {
cb.addTemplate(page, 0, -1f, 1f, 0, 0, pageHeight);
//cb.addTemplate(page, 0, 1f, -1f, 0, pageWidth, 0);
//rotationEvent.setRotation(PdfPage.SEASCAPE);
}
}
doc.close();
return pdfOut;
}