PDFsharp & MigraDoc Foundation

Determining a clipping region from CropBox
Page 1 of 1

Author:  wim [ Tue May 24, 2016 8:46 pm ]
Post subject:  Determining a clipping region from CropBox

When trying to print within the CropBox (when set), I always ended up in the wrong places.
It took me a few hours to realize that the Location property is *not* relative to the top-left corner, but to the bottom-left corner.
For pages that are 180 degrees rotated, a rotation transformation is needed and the Location is relative to the bottom-right corner.

Eventually I came up with the following code to calculate a clip region where the drawing needs to take place.

                    var width = page.Width;
                    var height = page.Height;
                    var gfx = XGraphics.FromPdfPage(page, XGraphicsPdfPageOptions.Append);
                    var pgRect = new PdfRectangle(new XPoint(), new XPoint(gfx.PageSize.Width, gfx.PageSize.Height));
                    var crop = page.CropBox;
                    PdfRectangle clipRect = pgRect;

                    if (crop.Width > 0 && crop.Height > 0)
                        bool rotated = page.Rotate == 180;
                        var clipY1 = height - (crop.Height + crop.Y1);
                        var clipY2 = clipY1 + crop.Height;
                        var clipX1 = !rotated ? crop.X1 : width -(crop.Width + crop.X1);
                        var clipX2 = !rotated ? crop.X2 : clipX1 + crop.Width;
                        clipRect = new PdfRectangle(new XPoint(clipX1, clipY1), new XPoint(clipX2, clipY2));
                            gfx.RotateAtTransform(180, new XPoint(width / 2.0, height / 2.0));

Page 1 of 1 All times are UTC
Powered by phpBB® Forum Software © phpBB Group