7
votes

I'm creating a web app that will be used for maintaining PDF documents in our database that come in through an automated system when we receive faxes. Users need to be able to review these documents, and one of the more common things they need to be able to do with these documents is flip/rotate individual pages when they were put into the fax machine the wrong way. This is almost always a 180 degree rotation of the page. I've created a function to do this, which seems to work, but only the first time its called. Any subsequent calls to this function don't seem to work anymore. Another strange thing associated with this function, is that I've also got another method that gets called that will add some text to the document at selected locations. I pass in the text and some coordinates, and it writes the text at those coordinates in the document, and all is well. The problem with this is, after the document is rotated (the one time it will rotate), if a user tries to add text to the document somewhere, it seems to reverse the coordinates it places the text at, and the text is upside down.

All of this tells me that, ultimately, I'm doing the page rotation wrong somehow. I can't seem to find any good samples of how to rotate a page in a PdfSharp document the correct way, so some guidance would be tremendously helpful and very much appreciated. Thanks in advance.

Here's the code I'm currently using for rotating pages, and adding text to pages:

// This is how I'm rotating the page...
public PdfDocument FlipPage(byte[] documentSource, int pageNumber)
{
    using (var stream = new MemoryStream())
    {
        stream.Write(documentSource, 0, documentSource.Length);
        var document = PdfReader.Open(stream);
        var page = document.Pages[pageNumber - 1];
        page.Rotate = 180;

        return document;
    }
}

// This is how I'm adding text to a page...
public static void AddTextToPage(this PdfDocument document, int pageNumber, Annotation annotation)
{
    var page = document.Pages[pageNumber - 1];
    annotation.TargetHeight = page.Height.Value;
    annotation.TargetWidth = page.Width.Value;

    var graphics = XGraphics.FromPdfPage(page);
    var textFormatter = new XTextFormatter(graphics);
    var font = new XFont("Arial", 10, XFontStyle.Regular);
    graphics.DrawString(annotation.Text, font, XBrushes.Red, new PointF((float)annotation.TargetX, (float)annotation.TargetY));
}
1
check this: graphics.RotateTransform(180) – Reza ArabQaeni
That compiles and succeeds, but it does nothing to the page at all. – Bob Yexley

1 Answers

7
votes

That's not my area of expertise, but instead of "page.Rotate = 180;" I'd try something like that:

page.Rotate = (page.Rotate + 180) % 360;

(code not tested, may require a cast)

When adding text, you can test for "page.Rotate == 180" and use different code then (like "graphics.RotateTransform(180)").