- Add a link to PDF with an external destination
- Add a link with an internal destination to PDF
- Add a note to PDF
- Add barcodes to PDF
- Add bookmarks to PDF
- Add footer to PDF
- Add simple html text to PDF
- Add hyperlink to PDF
- Add Long Term Validation (LTV) data to an existing signature
- Add multiline text to a PDF document
- Add a rubber stamp annotation with a custom icon
- Add single-line text to PDF
- Add Stamp to PDF
- Add tags to existing PDF
- Add text field to PDF
- Add a Diagonal Watermark to PDF in C# - TallComponents - PDF Library
- pdfkit5 - detailed changes to the API - Tall Components
- Append two or more existing PDF files
- Change the color inside a PDF
- Change the formatting of a numeric field
- Change page orientation PDF
- Clip PDF page content in C#
- .NET Core console app on MacOS
- Convert PDF to plain text
- Convert SVG to PDF
- Create a text annotation in PDF with rich text
- Create formfields in PDF documents
- Create a new digitally signed PDF document
- Create rectangles with rounded corners
- Create tagged PDF
- Create text with decorations
- How to create a tiling for shapes in PDF
- Crop content on a PDF page
- Determine the content bounding box
- Determine if a PDF only contains images
- Digitally sign a PDF form in C# or VB.NET
- Disable submit button after submitting
- How to downscale all images in a PDF
- Download and convert image to PDF
- How to downscale all images in a PDF
- Vector graphics in PDF
- Fill XFA form and export XDP data
- Fill and save dynamic XFA form
- Merge XDP data with dynamic XFA form
- Dynamic XFA
- How to embed files in a PDF document
- Embed TrueType font in PDF
- EMF to PDF as vector image
- Export FDF from PDF form
- Extract embedded files from PDF
- Extract glyph boxes from PDF
- Extract glyphs and sort by reading order
- Extract graphics from PDF
- Extract images from PDF
- Fill in a template PDF document
- Fill PDF form
- Fit image to PDF page
- Flatten Markup Annotation
- Flatten PDF form
- How to generate and export certificates
- How do I extract page destinations from bookmarks?
- Highlight fields in PDF
- How to add autosized text to PDF
- How to sign and verify updates to a PDF document
- Import FDF into PDF
- Licensing and .NET Standard
- Merge PDF files in C# .NET
- How to mirror PDF pages and other shapes
- Layout text with MultilineTextShape
- pdfkit5 and .NET Core
- pdfkit5 .NET Standard API
- Read and write meta data from PDF
- Read PDF tags
- How to reduce PDF file size
- Reduce PDF size
- Remove graphics from PDF
- Remove PDF security settings
- Replace field with image
- Resize PDF pages
- Rotate a PDF page
- How to scale content of PDF
- Search text in PDF
- PDF Viewer Preferences
- Create a custom signature handler to sign and verify PDF documents
- Split PDF pages in C# and VB.NET
- Tagged PDF
- TIFF to PDF C#
- Translate PDF page content
- Use multiple licenses
- Use TrueType font collections
- Write Document to HttpResponse
- Use pdfkit5 with a Xamarin.Forms app
- pdfkit5 and Xamarin
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