I have code below that crops the PDF page and then creates a new Document with cropped pdf page.
The code works fine as long as the source pdf page is not rotated. However,when source page has rotation then code is not able to set the page’s CropBox property. Page.CropBox property does not change.
Background
The page’s original Width = 1008 and Original Height = 612. I rotated the page using FoxIt and saved. When the code loads the rotated page, the MediaBox and CropBox property still shows Width = 1008 and Height = 612 ( the rotated page “notworking.pdf” is included in the attached zip)
static void Main(string[] args)
{
SetLicense();
// load source documents
// NOTE: The source document's page is already rotated by 270
// sourcePage.Rotate is on270
var sourceFile = AppDomain.CurrentDomain.BaseDirectory + "NotWorking.pdf";
var sourcePdf = new Document(sourceFile);
var sourcePage = sourcePdf.Pages[1];
var sourcedimension = sourcePage.GetPageRect(true);
var cropBox = new CartesianCropBox()
{
LLX = 0,
LLY = 658, //Y Axis
URX = sourcedimension.Width,
URY = sourcedimension.Height,
Height = sourcedimension.Height - 658, // URY - LLY
Width = sourcedimension.Width,
};
var image = GetCroppedImage(sourcePdf.Pages[1], cropBox);
// create new document and set page size
var newDoc = new Document();
var newPage = newDoc.Pages.Add();
newPage.SetPageSize(sourcedimension.Width, sourcedimension.Height);
// add cropped image to page
newPage.Paragraphs.Add(image);
// save document
newDoc.Save(_outputDir + "\\out.pdf");
}
private static Aspose.Pdf.Image GetCroppedImage(Aspose.Pdf.Page sourcePage, CartesianCropBox cropBox)
{
Aspose.Pdf.Image img = new Image();
Aspose.Pdf.Rectangle pageRect = new Rectangle(cropBox.LLX, cropBox.LLY, cropBox.URX, cropBox.URY);
// Issue here ??????????
// the sourcePage.CropBox does not get set when page has rotation
sourcePage.CropBox = pageRect;
img.FixHeight = cropBox.Height;
img.FixWidth = cropBox.Width;
// Create Image device with specified attributes
JpegDevice imgDevice = new JpegDevice(new Resolution(1920, 1080));
img.ImageStream = new MemoryStream();
// Convert a particular page and save the image to stream
imgDevice.Process(sourcePage, img.ImageStream);
img.ImageStream.Seek(0L, SeekOrigin.Begin);
// save image for testing purpose
using (var fs = new FileStream(_outputDir + "\\out.jpeg", FileMode.Create, FileAccess.Write))
{
img.ImageStream.CopyTo(fs);
}
img.ImageStream.Seek(0L, SeekOrigin.Begin);
return img;
}
I have attached the complete solution with working.pdf
and notworking.pdf
file. The solution needs to rebuild to get aspose.pdf nuget package
Cropper.zip (476.2 KB)