0

i am using C# with iTextSharp to rotate a page in a PDF file, for this i use this code

filname = @"C:\tr\jbklk.pdf";
using (FileStream outStream = new FileStream(filname, FileMode.Create))
{
    iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(@"C:\tr\2.pdf");
    iTextSharp.text.pdf.PdfStamper stamper = new iTextSharp.text.pdf.PdfStamper(reader, outStream);

    iTextSharp.text.pdf.PdfDictionary pageDict = reader.GetPageN(2);
    int desiredRot = 90; // 90 degrees clockwise from what it is now
    iTextSharp.text.pdf.PdfNumber rotation = pageDict.GetAsNumber(iTextSharp.text.pdf.PdfName.ROTATE);

    if (rotation != null)
    {
        desiredRot += rotation.IntValue;
        desiredRot %= 360; // must be 0, 90, 180, or 270
    }
    pageDict.Put(iTextSharp.text.pdf.PdfName.ROTATE, new iTextSharp.text.pdf.PdfNumber(desiredRot));

    stamper.Close();
}

this means that i have to create a new file and rotate the page in this new file is there any way to rotate the page in the same source file without creating a new file? thanks

Domysee
  • 12,718
  • 10
  • 53
  • 84
Bari
  • 75
  • 1
  • 8
  • 1
    PDF manipulation in iText(Sharp) by design does not support immediately writing to a file the document initially was directly loaded from. What you can do, though, is either first reading the file into a `byte[]`, opening a `PdfReader` from that `byte[]`, and stamping into the original file. Or reading from file but stamping into a memory stream and finally writing the stream content into the original file. – mkl Nov 16 '15 at 09:20

1 Answers1

0

You can use a MemoryStream for your Stamper and overwrite the source file.

This is an example in VB.NET:

Dim strYourPDFFileToRotate As String = "C:\tr\2.pdf"

Dim itsReader As New iTextSharp.text.pdf.PdfReader(System.IO.File.ReadAllBytes(strYourPDFFileToRotate))

Dim msOut As New System.IO.MemoryStream()

Dim itsStamper As New iTextSharp.text.pdf.PdfStamper(itsReader, msOut)

itsReader.GetPageN(1).Put(iTextSharp.text.pdf.PdfName.ROTATE, New iTextSharp.text.pdf.PdfNumber(90))

itsStamper.Close()
itsReader.Close()

System.IO.File.WriteAllBytes(strYourPDFFileToRotate, msOut.ToArray)

msOut.Close()
tezzo
  • 10,858
  • 1
  • 25
  • 48