8

I am trying to use a PDF for stamping and need to rotate it 90 degrees to lay it on correctly? Anyone know how to do this? Can't seem to find it online.

Casey ScriptFu Pharr
  • 1,672
  • 1
  • 16
  • 36
  • 1
    You bind a `PdfStamper` to `PdfReader` but before you do that you are free to manipulate the PDF using any methods available from the `PdfReader` object. See the [official sample here](http://itextpdf.com/examples/iia.php?id=232) in Java or a very similar but not exactly same [question here](http://stackoverflow.com/a/5349641/231316) in C#. – Chris Haas Nov 19 '14 at 16:04

2 Answers2

12

The Rotate90Degrees example uses PdfReader to get an instance of the document then changes the /Rotate value in every page dictionary. If there is no such entry, a /Rotate entry with value 90 is added:

final PdfReader reader = new PdfReader(source);
final int pagesCount = reader.getNumberOfPages();

for (int n = 1; n <= pagesCount; n++) {
    final PdfDictionary page = reader.getPageN(n);
    final PdfNumber rotate = page.getAsNumber(PdfName.ROTATE);
    final int rotation =
            rotate == null ? 90 : (rotate.intValue() + 90) % 360;

    page.put(PdfName.ROTATE, new PdfNumber(rotation));
}

Once this is done, we use a PdfStamper to persist the change:

PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.close();
reader.close();

This is for iText Java. For iTextSharp, porting Java to C# is easy as the terminology is identical. Change some lower cases into upper cases like this:

PdfDictionary page = reader.GetPageN(1);
page.Put(PdfName.ROTATE, new PdfNumber(90));

There's a more or less identical code snippet in the question part of this post: How to rotate PDF page with iTextSharp without causing error in ghostscript?

Community
  • 1
  • 1
Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
  • So I've used this code snippet in C# to rotate each page in a document and then I've used page.GetBytes() to get the bytes for the stream, but how do I go about recombining the pages into a single stream of bytes representing the file? – Ciaran Gallagher Nov 08 '19 at 10:08
1

For C# coders:

I replaced Bruno's answer with C# code:

and yes it's working like a charm, also you can change the rotation number to 180,270, etc

            PdfReader reader = new PdfReader("Source.pdf");
            int pagesCount = reader.NumberOfPages;
            PdfDictionary page = reader.GetPageN(1);
            PdfNumber rotate = page.GetAsNumber(PdfName.ROTATE);
            page.Put(PdfName.ROTATE, new PdfNumber(90));
            FileStream fs = new FileStream("created.pdf", FileMode.Create, 
            FileAccess.Write, FileShare.None);
            PdfStamper stamper = new PdfStamper(reader, fs);