Crop content on a PDF page
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:
The cropped page:
const string inputFileName = @"..\..\inputdocuments\PackingLightBrochure.pdf";
using (var inputStream = new FileStream(inputFileName, FileMode.Open, FileAccess.Read))
{
//note that the coordinates are specified in
//the PDF coordinate system(left bottom corner)
const float x = 100;
const float y = 100;
const float width = 300;
const float height = 100;
// define a crop rectangle
var cropRectangle = new RectangleF(x, y, width, height);
// open the source document
var sourceDocument = new Document(inputStream);
// create the target document
var targetDocument = new Document();
// enumerate the pages in the source document
foreach (var sourcePage in sourceDocument.Pages)
{
ContentShape shapes = sourcePage.CreateShapes();
// The prune method will create a new set of shapes. It will throw
// away shapes that are outside the provided crop rectangle.
shapes = PruneShape(shapes, cropRectangle);
// location of the returned shapes is relative to the crop rectangle
// of the original page, so we need to move them.
shapes.Transform = new MatrixTransform(shapes.Transform).Translate(-x, -y);
// create new page and add the shapes
var page = new Page(cropRectangle.Width, cropRectangle.Height);
page.VisualOverlay.Add(shapes);
// add the page to the resulting document
targetDocument.Pages.Add(page);
}
// write the target document to disk
const string fileName = @"..\..\cropped.pdf";
using (var outFile = new FileStream(fileName, FileMode.Create, FileAccess.Write))
{
targetDocument.Write(outFile);
}
Process.Start(fileName);
}
Const inputFileName As String = "..\..\..\inputdocuments\PackingLightBrochure.pdf"
Using inputStream = New FileStream(inputFileName, FileMode.Open, FileAccess.Read)
'note that the coordinates are specified in
'the PDF coordinate system(left bottom corner)
Const x As Single = 100
Const y As Single = 100
Const width As Single = 300
Const height As Single = 100
' define a crop rectangle
Dim cropRectangle = New RectangleF(x, y, width, height)
' open the source document
Dim sourceDocument = New Document(inputStream)
' create the target document
Dim targetDocument = New Document()
' enumerate the pages in the source document
For Each sourcePage In sourceDocument.Pages
Dim shapes As ContentShape = sourcePage.CreateShapes()
' The prune method will create a new set of shapes. It will throw
' away shapes that are outside the provided crop rectangle.
shapes = PruneShape(shapes, cropRectangle)
' location of the returned shapes is relative to the crop rectangle
' of the original page, so we need to move them.
shapes.Transform = New MatrixTransform(shapes.Transform).Translate(-x, -y)
' create new page and add the shapes
Dim page = New Page(cropRectangle.Width, cropRectangle.Height)
page.VisualOverlay.Add(shapes)
' add the page to the resulting document
targetDocument.Pages.Add(page)
Next
' write the target document to disk
Const fileName As String = "..\..\cropped.pdf"
Using outFile = New FileStream(fileName, FileMode.Create, FileAccess.Write)
targetDocument.Write(outFile)
End Using
Process.Start(fileName)
End Using
The PruneShapes method will create a new set of shapes. It will throw away shapes that are outside the provided crop rectangle.
private static ContentShape PruneShape(ContentShape shape, RectangleF cropRectangle)
{
// transform the crop rectangle in order to get it
// in the coordinate space of the shape
cropRectangle = TransformRectangle(cropRectangle, shape.Transform);
// Shape rectangle provides a rectangle where resides the shape.
// Assume that shape resides in the crop rectangle.
RectangleF shapeRectangle = cropRectangle;
// get the shape rectangle
if (shape is ShapeCollection)
{
shapeRectangle = GetShapeCollectionRect(shape as ShapeCollection);
}
else if (shape is ImageShape)
{
shapeRectangle = GetImageRectangle(shape as ImageShape);
}
else if (shape is TextShape)
{
shapeRectangle = GetTextRectangle(shape as TextShape);
}
else if (shape is FreeHandShape)
{
shapeRectangle = GetPathRectangle(shape as FreeHandShape);
}
// does crop rectangle intersect the shape rectangle?
bool isInCroppedRectangle = cropRectangle.IntersectsWith(shapeRectangle);
if (shape is ShapeCollection)
{
// we need to prune the shapes that are contained in the collection
// when it is not clipped or resides in the cropped area
var shapeCollection = shape as ShapeCollection;
if (!shapeCollection.Clip || isInCroppedRectangle)
{
return PruneShapeCollection(shapeCollection, cropRectangle);
}
// otherwise return null
return null;
}
// we return the shape when it resides in the cropped area
if (isInCroppedRectangle)
return shape;
return null;
}
``` vb
Private Function PruneShape(shape As ContentShape, cropRectangle As RectangleF) As ContentShape
' transform the crop rectangle in order to get it
' in the coordinate space of the shape
cropRectangle = TransformRectangle(cropRectangle, shape.Transform)
' Shape rectangle provides a rectangle where resides the shape.
' Assume that shape resides in the crop rectangle.
Dim shapeRectangle As RectangleF = cropRectangle
' get the shape rectangle
If TypeOf shape Is ShapeCollection Then
shapeRectangle = GetShapeCollectionRect(TryCast(shape, ShapeCollection))
ElseIf TypeOf shape Is ImageShape Then
shapeRectangle = GetImageRectangle(TryCast(shape, ImageShape))
ElseIf TypeOf shape Is TextShape Then
shapeRectangle = GetTextRectangle(TryCast(shape, TextShape))
ElseIf TypeOf shape Is FreeHandShape Then
shapeRectangle = GetPathRectangle(TryCast(shape, FreeHandShape))
End If
' does crop rectangle intersect the shape rectangle?
Dim isInCroppedRectangle As Boolean = cropRectangle.IntersectsWith(shapeRectangle)
If TypeOf shape Is ShapeCollection Then
' we need to prune the shapes that are contained in the collection
' when it is not clipped or resides in the cropped area
Dim shapeCollection = TryCast(shape, ShapeCollection)
If Not shapeCollection.Clip OrElse isInCroppedRectangle Then
Return PruneShapeCollection(shapeCollection, cropRectangle)
End If
' otherwise return null
Return Nothing
End If
' we return the shape when it resides in the cropped area
If isInCroppedRectangle Then
Return shape
End If
Return Nothing
End Function
The TransformRectangle method applies provided transformation to the specified rectangle.
private static RectangleF TransformRectangle(RectangleF rect, Transform transform)
{
System.Drawing.Drawing2D.Matrix matrix = transform.CreateGdiMatrix();
matrix.Invert();
var p1 = new PointF(rect.Left, rect.Bottom);
var p2 = new PointF(rect.Right, rect.Top);
var points = new[] { p1, p2 };
matrix.TransformPoints(points);
p1 = points[0];
p2 = points[1];
float x = Math.Min(p1.X, p2.X);
float y = Math.Min(p1.Y, p2.Y);
float width = Math.Abs(p1.X - p2.X);
float height = Math.Abs(p1.Y - p2.Y);
return new RectangleF(x, y, width, height);
}
Private Function TransformRectangle(rect As RectangleF, transform As Transform) As RectangleF
Dim matrix As System.Drawing.Drawing2D.Matrix = transform.CreateGdiMatrix()
matrix.Invert()
Dim p1 = New PointF(rect.Left, rect.Bottom)
Dim p2 = New PointF(rect.Right, rect.Top)
Dim points = {p1, p2}
matrix.TransformPoints(points)
p1 = points(0)
p2 = points(1)
Dim x As Single = Math.Min(p1.X, p2.X)
Dim y As Single = Math.Min(p1.Y, p2.Y)
Dim width As Single = Math.Abs(p1.X - p2.X)
Dim height As Single = Math.Abs(p1.Y - p2.Y)
Return New RectangleF(x, y, width, height)
End Function
The PruneShapeCollection method will create a new set of shapes. It will throw away shapes that are outside the provided crop rectangle.
private static ContentShape PruneShapeCollection(ShapeCollection shapes, RectangleF cropRectangle)
{
var result = new ShapeCollection(shapes.Width, shapes.Height);
foreach (var shape in shapes)
{
var contentShape = shape as ContentShape;
if (contentShape != null)
{
Shape prunedShape = PruneShape(contentShape, cropRectangle);
if (prunedShape != null)
{
result.Add(prunedShape);
}
}
else
{
// Keep shapes that are not content shapes.
result.Add(shape);
}
}
result.Transform = shapes.Transform;
result.BlendMode = shapes.BlendMode;
result.Clip = shapes.Clip;
result.Dock = shapes.Dock;
result.Margin = shapes.Margin;
result.Opacity = shapes.Opacity;
return result;
}
Private Function PruneShapeCollection(shapes As ShapeCollection, cropRectangle As RectangleF) As ContentShape
Dim result = New ShapeCollection(shapes.Width, shapes.Height)
For Each shape In shapes
Dim contentShape = TryCast(shape, ContentShape)
If contentShape IsNot Nothing Then
Dim prunedShape As Shape = PruneShape(contentShape, cropRectangle)
If prunedShape IsNot Nothing Then
result.Add(prunedShape)
End If
Else
' Keep shapes that are not content shapes.
result.Add(shape)
End If
Next
result.Transform = shapes.Transform
result.BlendMode = shapes.BlendMode
result.Clip = shapes.Clip
result.Dock = shapes.Dock
result.Margin = shapes.Margin
result.Opacity = shapes.Opacity
Return result
End Function
Here are a number of methods that return a boundary rectangle of a specific shape.
private static RectangleF GetImageRectangle(ImageShape imageShape)
{
return new RectangleF(0, 0, (float)imageShape.Width, (float)imageShape.Height);
}
private static RectangleF GetTextRectangle(TextShape textShape)
{
return new RectangleF(0, 0, (float)textShape.MeasuredWidth, (float)textShape.MeasuredHeight);
}
private static RectangleF GetShapeCollectionRect(ShapeCollection shapeCollection)
{
return new RectangleF(0, 0, (float)shapeCollection.Width, (float)shapeCollection.Height);
}
private static RectangleF GetPathRectangle(FreeHandShape freehandShape)
{
double minX = double.MaxValue;
double minY = double.MaxValue;
double maxX = double.MinValue;
double maxY = double.MinValue;
foreach (var path in freehandShape.Paths)
{
foreach (var segment in path.Segments)
{
var bezierSegment = segment as FreeHandBezierSegment;
if (bezierSegment != null)
{
minX = Math.Min(minX, bezierSegment.X1);
minX = Math.Min(minX, bezierSegment.X2);
minX = Math.Min(minX, bezierSegment.X3);
maxX = Math.Max(maxX, bezierSegment.X1);
maxX = Math.Max(maxX, bezierSegment.X2);
maxX = Math.Max(maxX, bezierSegment.X3);
minY = Math.Min(minY, bezierSegment.Y1);
minY = Math.Min(minY, bezierSegment.Y2);
minY = Math.Min(minY, bezierSegment.Y3);
maxY = Math.Max(maxY, bezierSegment.Y1);
maxY = Math.Max(maxY, bezierSegment.Y2);
maxY = Math.Max(maxY, bezierSegment.Y3);
}
var lineSegment = segment as FreeHandLineSegment;
if (lineSegment != null)
{
minX = Math.Min(minX, lineSegment.X1);
maxX = Math.Max(maxX, lineSegment.X1);
minY = Math.Min(minY, lineSegment.Y1);
maxY = Math.Max(maxY, lineSegment.Y1);
}
var startSegment = segment as FreeHandStartSegment;
if (startSegment != null)
{
minX = Math.Min(minX, startSegment.X);
maxX = Math.Max(maxX, startSegment.X);
minY = Math.Min(minY, startSegment.Y);
maxY = Math.Max(maxY, startSegment.Y);
}
}
}
return new RectangleF((float)minX, (float)minY,
(float)Math.Abs(maxX - minX),
(float)Math.Abs(maxY - minY));
}
Private Function GetImageRectangle(imageShape As ImageShape) As RectangleF
Return New RectangleF(0, 0, CSng(imageShape.Width), CSng(imageShape.Height))
End Function
Private Function GetTextRectangle(textShape As TextShape) As RectangleF
Return New RectangleF(0, 0, CSng(textShape.MeasuredWidth), CSng(textShape.MeasuredHeight))
End Function
Private Function GetShapeCollectionRect(shapeCollection As ShapeCollection) As RectangleF
Return New RectangleF(0, 0, CSng(shapeCollection.Width), CSng(shapeCollection.Height))
End Function
Private Function GetPathRectangle(freehandShape As FreeHandShape) As RectangleF
Dim minX As Double = Double.MaxValue
Dim minY As Double = Double.MaxValue
Dim maxX As Double = Double.MinValue
Dim maxY As Double = Double.MinValue
For Each path In freehandShape.Paths
For Each segment In path.Segments
Dim bezierSegment = TryCast(segment, FreeHandBezierSegment)
If bezierSegment IsNot Nothing Then
minX = Math.Min(minX, bezierSegment.X1)
minX = Math.Min(minX, bezierSegment.X2)
minX = Math.Min(minX, bezierSegment.X3)
maxX = Math.Max(maxX, bezierSegment.X1)
maxX = Math.Max(maxX, bezierSegment.X2)
maxX = Math.Max(maxX, bezierSegment.X3)
minY = Math.Min(minY, bezierSegment.Y1)
minY = Math.Min(minY, bezierSegment.Y2)
minY = Math.Min(minY, bezierSegment.Y3)
maxY = Math.Max(maxY, bezierSegment.Y1)
maxY = Math.Max(maxY, bezierSegment.Y2)
maxY = Math.Max(maxY, bezierSegment.Y3)
End If
Dim lineSegment = TryCast(segment, FreeHandLineSegment)
If lineSegment IsNot Nothing Then
minX = Math.Min(minX, lineSegment.X1)
maxX = Math.Max(maxX, lineSegment.X1)
minY = Math.Min(minY, lineSegment.Y1)
maxY = Math.Max(maxY, lineSegment.Y1)
End If
Dim startSegment = TryCast(segment, FreeHandStartSegment)
If startSegment IsNot Nothing Then
minX = Math.Min(minX, startSegment.X)
maxX = Math.Max(maxX, startSegment.X)
minY = Math.Min(minY, startSegment.Y)
maxY = Math.Max(maxY, startSegment.Y)
End If
Next
Next
Return New RectangleF(CSng(minX), CSng(minY), CSng(Math.Abs(maxX - minX)), CSng(Math.Abs(maxY - minY)))
End Function
No results
Add Long Term Validation (LTV) data to an existing signature
Render PDF to multipage color TIFF
Render PDF page to Skia surface
Render PDF page as PNG
How to downscale all images in a PDF
How to generate and export certificates
How to downscale all images in a PDF
Add Stamp to PDF
How to use a system font for rendering text
Customize the GUI interaction of a radio button
Customize the UI interaction of a check box
PDF to grayscale TIFF
How to reduce PDF file size
How do I create graphics with Icc based colors
Highlight fields in PDF
Add a note to PDF
Display PDF in a WPF app and stay responsive – the code
Draw interactively on a PDF page
Resize PDF pages
Verify a custom digital PDF signature
C# Print PDF documents from a WPF application
Extract glyph boxes from PDF
Use TrueType font collections
Layout text with MultilineTextShape
Calculate the height of a paragraph in PDF
Merge PDF files in C# .NET
How do I extract page destinations from bookmarks?
Clip PDF page content in C#
How do I use PDFControls.NET in a WPF application
Fill PDF form
Extract glyphs and sort by reading order
Add bookmarks to PDF
How to scale content of PDF
Create rectangles with rounded corners
Create text with decorations
Create layers in PDF and draw on each layer
Multipage TIFF to PDF
TIFF to PDF C#
Crop content on a PDF page
How to embed files in a PDF document
Remove graphics from PDF
Change the color inside a PDF
Create PDF in C#
Text formatting
Import FDF into PDF
Flatten PDF form
Digitally sign a PDF form in C# or VB.NET
Vector graphics in PDF
Translate PDF page content
Extract graphics from PDF
Determine the content bounding box
How to add page numbers to your PDF
Create / impose PDF 2-up
Search text in PDF
Append multiple PDF documents
Convert PDF to plain text
Flatten Markup Annotation
Add text field to PDF
Extract embedded files from PDF
Extract images from PDF
Add a Diagonal Watermark to PDF in C#
Fit image to PDF page
Add simple html text to PDF
Add multiline text to a PDF document
Add single-line text to PDF
Create a new digitally signed PDF document
PDF Viewer Preferences
Change page orientation PDF
Split PDF pages in C# and VB.NET
Append two or more existing PDF files
Change colors of black-and-white TIFF after converting from PDF
Determine if a PDF only contains images
Add footer to PDF
Convert SVG to PDF
Fill in a PDF form using MVC
C# render pdf in browser using MVC
Convert XHTML to PDF
Add hyperlink to PDF
Rotate a PDF page
Change the formatting of a numeric field
How to mirror PDF pages and other shapes
Fill in a template PDF document
How to add autosized text to PDF
Create formfields in PDF documents
Export FDF from PDF form
Add a link with an internal destination to PDF
Remove PDF security settings
Add a link to PDF with an external destination
How to sign and verify updates to a PDF document
Convert PDF to PNG using WPF
Embed TrueType font
Override MouseWheel event
Convert PDF to an image using a dither matrix
Font mapping
Convert PDF with layers to image
C# Print PDF Document
Render PDF with ResolveFont event handler
Render PDF to EMF
Convert PDF to XPS
How to create a thumbnail viewer
How to create a tiling for shapes in PDF
Add footer with left and right aligned text on same line
Convert PDF to JPG in C#
EMF to PDF as vector image
EMF to PDF as raster image
Replace field with image
Add a rubber stamp annotation with a custom icon
Create a text annotation in PDF with rich text
XhtmlParagraph and TrueType fonts
What is the resulting fontsize in PDF for rich text used in a SimpleXhtmlShape
Read and write meta data from PDF
Create a custom signature handler to sign and verify PDF documents
Merge PDF
Stitch PDF documents
Download and convert image to PDF
Convert TXT to PDF
Add barcodes to PDF
Convert PDF to multipage TIFF in C# .NET
Convert multiple PDF pages to bitmap
Render a PDF to bitmap
Bulleted list from XML and XSL
Tagged PDF
PDFKit.NET 5.0 – detailed changes to the API
Create tagged PDF
PDFKit.NET 5.0 and .NET Core
PDFKit.NET 5.0 and Xamarin
Dynamic XFA
PDFKit.NET 5.0 .NET Standard API
.NET Core console app on MacOS
Add tags to existing PDF
Read PDF tags
Merge XDP data with dynamic XFA form
Fill XFA form and export XDP data
Fill and save dynamic XFA form
Use PDFKit.NET 5.0 with a Xamarin.Forms app
Use multiple licenses
Licensing and .NET Standard
Reduce PDF size
Generate PDF form from XML
Generate PDF with local images from XML with Xamarin.iOS
Disable submit button after submitting
Write Document to HttpResponse