Crop content on a PDF page

Manipulate PDF, Shapes
6/12/2014

Downloads

This code sample shows how to remove all content that is outside a crop rectangle.

In the main method we enumerate all the pages in the PDF document and reduce the collection of shapes leaving only those shapes that reside within specified crop rectangle.

The original page:

page.png

The cropped page:

result.png

C# code sample

1 const string inputFileName = @"..\..\inputdocuments\PackingLightBrochure.pdf"; 2 using (var inputStream = new FileStream(inputFileName, FileMode.Open, FileAccess.Read)) 3 { 4 //note that the coordinates are specified in 5 //the PDF coordinate system(left bottom corner) 6 const float x = 100; 7 const float y = 100; 8 const float width = 300; 9 const float height = 100; 10 11 // define a crop rectangle 12 var cropRectangle = new RectangleF(x, y, width, height); 13 14 // open the source document 15 var sourceDocument = new Document(inputStream); 16 17 // create the target document 18 var targetDocument = new Document(); 19 20 // enumerate the pages in the source document 21 foreach (var sourcePage in sourceDocument.Pages) 22 { 23 ContentShape shapes = sourcePage.CreateShapes(); 24 25 // The prune method will create a new set of shapes. It will throw 26 // away shapes that are outside the provided crop rectangle. 27 shapes = PruneShape(shapes, cropRectangle); 28 29 // location of the returned shapes is relative to the crop rectangle 30 // of the original page, so we need to move them. 31 shapes.Transform = new MatrixTransform(shapes.Transform).Translate(-x, -y); 32 33 // create new page and add the shapes 34 var page = new Page(cropRectangle.Width, cropRectangle.Height); 35 page.VisualOverlay.Add(shapes); 36 37 // add the page to the resulting document 38 targetDocument.Pages.Add(page); 39 } 40 41 // write the target document to disk 42 const string fileName = @"..\..\cropped.pdf"; 43 using (var outFile = new FileStream(fileName, FileMode.Create, FileAccess.Write)) 44 { 45 targetDocument.Write(outFile); 46 } 47 48 Process.Start(fileName); 49 }

VB.NET code sample

1 Const inputFileName As String = "..\..\..\inputdocuments\PackingLightBrochure.pdf" 2 Using inputStream = New FileStream(inputFileName, FileMode.Open, FileAccess.Read) 3 'note that the coordinates are specified in 4 'the PDF coordinate system(left bottom corner) 5 Const x As Single = 100 6 Const y As Single = 100 7 Const width As Single = 300 8 Const height As Single = 100 9 10 ' define a crop rectangle 11 Dim cropRectangle = New RectangleF(x, y, width, height) 12 13 ' open the source document 14 Dim sourceDocument = New Document(inputStream) 15 16 ' create the target document 17 Dim targetDocument = New Document() 18 19 ' enumerate the pages in the source document 20 For Each sourcePage In sourceDocument.Pages 21 Dim shapes As ContentShape = sourcePage.CreateShapes() 22 23 ' The prune method will create a new set of shapes. It will throw 24 ' away shapes that are outside the provided crop rectangle. 25 shapes = PruneShape(shapes, cropRectangle) 26 27 ' location of the returned shapes is relative to the crop rectangle 28 ' of the original page, so we need to move them. 29 shapes.Transform = New MatrixTransform(shapes.Transform).Translate(-x, -y) 30 31 ' create new page and add the shapes 32 Dim page = New Page(cropRectangle.Width, cropRectangle.Height) 33 page.VisualOverlay.Add(shapes) 34 35 ' add the page to the resulting document 36 targetDocument.Pages.Add(page) 37 Next 38 39 ' write the target document to disk 40 Const fileName As String = "..\..\cropped.pdf" 41 Using outFile = New FileStream(fileName, FileMode.Create, FileAccess.Write) 42 targetDocument.Write(outFile) 43 End Using 44 45 Process.Start(fileName) 46 End Using

The PruneShapes method will create a new set of shapes. It will throw away shapes that are outside the provided crop rectangle.

C# code sample

1 private static ContentShape PruneShape(ContentShape shape, RectangleF cropRectangle) 2 { 3 // transform the crop rectangle in order to get it 4 // in the coordinate space of the shape 5 cropRectangle = TransformRectangle(cropRectangle, shape.Transform); 6 7 // Shape rectangle provides a rectangle where resides the shape. 8 // Assume that shape resides in the crop rectangle. 9 RectangleF shapeRectangle = cropRectangle; 10 11 // get the shape rectangle 12 if (shape is ShapeCollection) 13 { 14 shapeRectangle = GetShapeCollectionRect(shape as ShapeCollection); 15 } 16 else if (shape is ImageShape) 17 { 18 shapeRectangle = GetImageRectangle(shape as ImageShape); 19 } 20 else if (shape is TextShape) 21 { 22 shapeRectangle = GetTextRectangle(shape as TextShape); 23 } 24 else if (shape is FreeHandShape) 25 { 26 shapeRectangle = GetPathRectangle(shape as FreeHandShape); 27 } 28 29 // does crop rectangle intersect the shape rectangle? 30 bool isInCroppedRectangle = cropRectangle.IntersectsWith(shapeRectangle); 31 32 if (shape is ShapeCollection) 33 { 34 // we need to prune the shapes that are contained in the collection 35 // when it is not clipped or resides in the cropped area 36 var shapeCollection = shape as ShapeCollection; 37 if (!shapeCollection.Clip || isInCroppedRectangle) 38 { 39 return PruneShapeCollection(shapeCollection, cropRectangle); 40 } 41 // otherwise return null 42 return null; 43 } 44 45 // we return the shape when it resides in the cropped area 46 if (isInCroppedRectangle) 47 return shape; 48 49 return null; 50 }

VB.NET code sample

1 Private Function PruneShape(shape As ContentShape, cropRectangle As RectangleF) As ContentShape 2 ' transform the crop rectangle in order to get it 3 ' in the coordinate space of the shape 4 cropRectangle = TransformRectangle(cropRectangle, shape.Transform) 5 6 ' Shape rectangle provides a rectangle where resides the shape. 7 ' Assume that shape resides in the crop rectangle. 8 Dim shapeRectangle As RectangleF = cropRectangle 9 10 ' get the shape rectangle 11 If TypeOf shape Is ShapeCollection Then 12 shapeRectangle = GetShapeCollectionRect(TryCast(shape, ShapeCollection)) 13 ElseIf TypeOf shape Is ImageShape Then 14 shapeRectangle = GetImageRectangle(TryCast(shape, ImageShape)) 15 ElseIf TypeOf shape Is TextShape Then 16 shapeRectangle = GetTextRectangle(TryCast(shape, TextShape)) 17 ElseIf TypeOf shape Is FreeHandShape Then 18 shapeRectangle = GetPathRectangle(TryCast(shape, FreeHandShape)) 19 End If 20 21 ' does crop rectangle intersect the shape rectangle? 22 Dim isInCroppedRectangle As Boolean = cropRectangle.IntersectsWith(shapeRectangle) 23 24 If TypeOf shape Is ShapeCollection Then 25 ' we need to prune the shapes that are contained in the collection 26 ' when it is not clipped or resides in the cropped area 27 Dim shapeCollection = TryCast(shape, ShapeCollection) 28 If Not shapeCollection.Clip OrElse isInCroppedRectangle Then 29 Return PruneShapeCollection(shapeCollection, cropRectangle) 30 End If 31 ' otherwise return null 32 Return Nothing 33 End If 34 35 ' we return the shape when it resides in the cropped area 36 If isInCroppedRectangle Then 37 Return shape 38 End If 39 40 Return Nothing 41 End Function

The TransformRectangle method applies provided transformation to the specified rectangle.

C# code sample

1 private static RectangleF TransformRectangle(RectangleF rect, Transform transform) 2 { 3 System.Drawing.Drawing2D.Matrix matrix = transform.CreateGdiMatrix(); 4 matrix.Invert(); 5 6 var p1 = new PointF(rect.Left, rect.Bottom); 7 var p2 = new PointF(rect.Right, rect.Top); 8 9 var points = new[] { p1, p2 }; 10 matrix.TransformPoints(points); 11 12 p1 = points[0]; 13 p2 = points[1]; 14 15 float x = Math.Min(p1.X, p2.X); 16 float y = Math.Min(p1.Y, p2.Y); 17 float width = Math.Abs(p1.X - p2.X); 18 float height = Math.Abs(p1.Y - p2.Y); 19 20 return new RectangleF(x, y, width, height); 21 }

VB.NET code sample

1 Private Function TransformRectangle(rect As RectangleF, transform As Transform) As RectangleF 2 Dim matrix As System.Drawing.Drawing2D.Matrix = transform.CreateGdiMatrix() 3 matrix.Invert() 4 5 Dim p1 = New PointF(rect.Left, rect.Bottom) 6 Dim p2 = New PointF(rect.Right, rect.Top) 7 8 Dim points = {p1, p2} 9 matrix.TransformPoints(points) 10 11 p1 = points(0) 12 p2 = points(1) 13 14 Dim x As Single = Math.Min(p1.X, p2.X) 15 Dim y As Single = Math.Min(p1.Y, p2.Y) 16 Dim width As Single = Math.Abs(p1.X - p2.X) 17 Dim height As Single = Math.Abs(p1.Y - p2.Y) 18 19 Return New RectangleF(x, y, width, height) 20 End Function

The PruneShapeCollection method will create a new set of shapes. It will throw away shapes that are outside the provided crop rectangle.

C# code sample

1 private static ContentShape PruneShapeCollection(ShapeCollection shapes, RectangleF cropRectangle) 2 { 3 var result = new ShapeCollection(shapes.Width, shapes.Height); 4 5 foreach (var shape in shapes) 6 { 7 var contentShape = shape as ContentShape; 8 9 if (contentShape != null) 10 { 11 Shape prunedShape = PruneShape(contentShape, cropRectangle); 12 if (prunedShape != null) 13 { 14 result.Add(prunedShape); 15 } 16 } 17 else 18 { 19 // Keep shapes that are not content shapes. 20 result.Add(shape); 21 } 22 } 23 result.Transform = shapes.Transform; 24 result.BlendMode = shapes.BlendMode; 25 result.Clip = shapes.Clip; 26 result.Dock = shapes.Dock; 27 result.Margin = shapes.Margin; 28 result.Opacity = shapes.Opacity; 29 30 return result; 31 }

VB.NET code sample

1 Private Function PruneShapeCollection(shapes As ShapeCollection, cropRectangle As RectangleF) As ContentShape 2 Dim result = New ShapeCollection(shapes.Width, shapes.Height) 3 4 For Each shape In shapes 5 Dim contentShape = TryCast(shape, ContentShape) 6 7 If contentShape IsNot Nothing Then 8 Dim prunedShape As Shape = PruneShape(contentShape, cropRectangle) 9 If prunedShape IsNot Nothing Then 10 result.Add(prunedShape) 11 End If 12 Else 13 ' Keep shapes that are not content shapes. 14 result.Add(shape) 15 End If 16 Next 17 result.Transform = shapes.Transform 18 result.BlendMode = shapes.BlendMode 19 result.Clip = shapes.Clip 20 result.Dock = shapes.Dock 21 result.Margin = shapes.Margin 22 result.Opacity = shapes.Opacity 23 24 Return result 25 End Function

Here are a number of methods that return a boundary rectangle of a specific shape.

C# code sample

1 private static RectangleF GetImageRectangle(ImageShape imageShape) 2 { 3 return new RectangleF(0, 0, (float)imageShape.Width, (float)imageShape.Height); 4 } 5 6 private static RectangleF GetTextRectangle(TextShape textShape) 7 { 8 return new RectangleF(0, 0, (float)textShape.MeasuredWidth, (float)textShape.MeasuredHeight); 9 } 10 11 private static RectangleF GetShapeCollectionRect(ShapeCollection shapeCollection) 12 { 13 return new RectangleF(0, 0, (float)shapeCollection.Width, (float)shapeCollection.Height); 14 } 15 16 private static RectangleF GetPathRectangle(FreeHandShape freehandShape) 17 { 18 double minX = double.MaxValue; 19 double minY = double.MaxValue; 20 double maxX = double.MinValue; 21 double maxY = double.MinValue; 22 23 foreach (var path in freehandShape.Paths) 24 { 25 foreach (var segment in path.Segments) 26 { 27 var bezierSegment = segment as FreeHandBezierSegment; 28 if (bezierSegment != null) 29 { 30 minX = Math.Min(minX, bezierSegment.X1); 31 minX = Math.Min(minX, bezierSegment.X2); 32 minX = Math.Min(minX, bezierSegment.X3); 33 maxX = Math.Max(maxX, bezierSegment.X1); 34 maxX = Math.Max(maxX, bezierSegment.X2); 35 maxX = Math.Max(maxX, bezierSegment.X3); 36 minY = Math.Min(minY, bezierSegment.Y1); 37 minY = Math.Min(minY, bezierSegment.Y2); 38 minY = Math.Min(minY, bezierSegment.Y3); 39 maxY = Math.Max(maxY, bezierSegment.Y1); 40 maxY = Math.Max(maxY, bezierSegment.Y2); 41 maxY = Math.Max(maxY, bezierSegment.Y3); 42 } 43 var lineSegment = segment as FreeHandLineSegment; 44 if (lineSegment != null) 45 { 46 minX = Math.Min(minX, lineSegment.X1); 47 maxX = Math.Max(maxX, lineSegment.X1); 48 minY = Math.Min(minY, lineSegment.Y1); 49 maxY = Math.Max(maxY, lineSegment.Y1); 50 } 51 var startSegment = segment as FreeHandStartSegment; 52 if (startSegment != null) 53 { 54 minX = Math.Min(minX, startSegment.X); 55 maxX = Math.Max(maxX, startSegment.X); 56 minY = Math.Min(minY, startSegment.Y); 57 maxY = Math.Max(maxY, startSegment.Y); 58 } 59 } 60 } 61 62 return new RectangleF((float)minX, (float)minY, 63 (float)Math.Abs(maxX - minX), 64 (float)Math.Abs(maxY - minY)); 65 }

VB.NET code sample

1 Private Function GetImageRectangle(imageShape As ImageShape) As RectangleF 2 Return New RectangleF(0, 0, CSng(imageShape.Width), CSng(imageShape.Height)) 3 End Function 4 5 Private Function GetTextRectangle(textShape As TextShape) As RectangleF 6 Return New RectangleF(0, 0, CSng(textShape.MeasuredWidth), CSng(textShape.MeasuredHeight)) 7 End Function 8 9 Private Function GetShapeCollectionRect(shapeCollection As ShapeCollection) As RectangleF 10 Return New RectangleF(0, 0, CSng(shapeCollection.Width), CSng(shapeCollection.Height)) 11 End Function 12 13 Private Function GetPathRectangle(freehandShape As FreeHandShape) As RectangleF 14 Dim minX As Double = Double.MaxValue 15 Dim minY As Double = Double.MaxValue 16 Dim maxX As Double = Double.MinValue 17 Dim maxY As Double = Double.MinValue 18 19 For Each path In freehandShape.Paths 20 For Each segment In path.Segments 21 Dim bezierSegment = TryCast(segment, FreeHandBezierSegment) 22 If bezierSegment IsNot Nothing Then 23 minX = Math.Min(minX, bezierSegment.X1) 24 minX = Math.Min(minX, bezierSegment.X2) 25 minX = Math.Min(minX, bezierSegment.X3) 26 maxX = Math.Max(maxX, bezierSegment.X1) 27 maxX = Math.Max(maxX, bezierSegment.X2) 28 maxX = Math.Max(maxX, bezierSegment.X3) 29 minY = Math.Min(minY, bezierSegment.Y1) 30 minY = Math.Min(minY, bezierSegment.Y2) 31 minY = Math.Min(minY, bezierSegment.Y3) 32 maxY = Math.Max(maxY, bezierSegment.Y1) 33 maxY = Math.Max(maxY, bezierSegment.Y2) 34 maxY = Math.Max(maxY, bezierSegment.Y3) 35 End If 36 Dim lineSegment = TryCast(segment, FreeHandLineSegment) 37 If lineSegment IsNot Nothing Then 38 minX = Math.Min(minX, lineSegment.X1) 39 maxX = Math.Max(maxX, lineSegment.X1) 40 minY = Math.Min(minY, lineSegment.Y1) 41 maxY = Math.Max(maxY, lineSegment.Y1) 42 End If 43 Dim startSegment = TryCast(segment, FreeHandStartSegment) 44 If startSegment IsNot Nothing Then 45 minX = Math.Min(minX, startSegment.X) 46 maxX = Math.Max(maxX, startSegment.X) 47 minY = Math.Min(minY, startSegment.Y) 48 maxY = Math.Max(maxY, startSegment.Y) 49 End If 50 Next 51 Next 52 53 Return New RectangleF(CSng(minX), CSng(minY), CSng(Math.Abs(maxX - minX)), CSng(Math.Abs(maxY - minY))) 54 End Function