Search code examples
itext

How do I cut off one half of a PDF page?


I want to print a DHL label using a label printer.

The DHL label consists of 2 parts: The left half of the image is just info that I can keep to myself. The right part of the PDF is what should actually be printed.

I would therefore like to cut away the left part of the PDF. I do not want to make it blank, but I really I want to cut if off.

How could I do this?

enter image description here


Solution

  • You essentially want to cut away one half of the PDF page; looking at you screenshot most likely the lower half.

    Using iTextSharp 5.5.13.3 you can do that like this:

    var testFile = @"new pdf1.pdf";
    var resultFile = @"new pdf1-Cut.pdf";
    
    using (PdfReader pdfReader = new PdfReader(testFile))
    using (PdfStamper pdfStamper = new PdfStamper(pdfReader, File.Create(resultFile)))
    {
        for (int i = 1; i <= pdfReader.NumberOfPages; i++)
        {
            Rectangle cropBox = pdfReader.GetCropBox(i);
            PdfArray newCropBox = new PdfArray(new float[] {
                    cropBox.Left, (cropBox.Bottom + cropBox.Top) / 2,
                    cropBox.Right, cropBox.Top });
    
            PdfDictionary pageDictionary = pdfReader.GetPageN(i);
            pageDictionary.Put(PdfName.CROPBOX, newCropBox);
            pageDictionary.Put(PdfName.MEDIABOX, newCropBox);
        }
    }
    

    (CutPages test CutInHalfForTmighty)

    Before After
    Screenshot original Screenshot cut