Crop Pdf from each edge using itextshap

1.2k views Asked by At

I am trying to crop pdf 5 mm from every edge i.e top,bottom,right and left. I tried with below code

public void TrimPdf(string sourceFilePath, string outputFilePath)
{
    PdfReader pdfReader = new PdfReader(sourceFilePath);
    float widthTo_Trim = iTextSharp.text.Utilities.MillimetersToPoints(5);

    using (FileStream output = new FileStream(outputFilePath, FileMode.Create, FileAccess.Write))
    using (PdfStamper pdfStamper = new PdfStamper(pdfReader, output))
    {
        for (int page = 1; page <= pdfReader.NumberOfPages; page++)
        {
            Rectangle cropBox = pdfReader.GetCropBox(page);

            cropBox.Left += widthTo_Trim;
            cropBox.Right += widthTo_Trim;
            cropBox.Top += widthTo_Trim;
            cropBox.Bottom += widthTo_Trim;

            pdfReader.GetPageN(page).Put(PdfName.CROPBOX, new PdfRectangle(cropBox));
        }
    }
}

By using this code i am Able to Crop only Left and Bottom part. unable to crop top and right side How can i get desire result ?

1

There are 1 answers

1
Narasappa On BEST ANSWER

This solved my problem by using Below code

public void TrimLeftandRightFoall(string sourceFilePath, string outputFilePath, float cropwidth)
{
    PdfReader pdfReader = new PdfReader(sourceFilePath);
    float width = (float)GetPDFwidth(sourceFilePath);
    float height = (float)GetPDFHeight(sourceFilePath);
    float widthTo_Trim = iTextSharp.text.Utilities.MillimetersToPoints(cropwidth);

    PdfRectangle rectLeftside = new PdfRectangle(widthTo_Trim, widthTo_Trim, width-widthTo_Trim , height-widthTo_Trim);

    using (var output = new FileStream(outputFilePath, FileMode.CreateNew, FileAccess.Write))
    {
        // Create a new document
        Document doc = new Document();

        // Make a copy of the document
        PdfSmartCopy smartCopy = new PdfSmartCopy(doc, output);

        // Open the newly created document
        doc.Open();

        // Loop through all pages of the source document
        for (int i = 1; i <= pdfReader.NumberOfPages; i++)
        {
            // Get a page
            var page = pdfReader.GetPageN(i);
            page.Put(PdfName.MEDIABOX, rectLeftside);

            var copiedPage = smartCopy.GetImportedPage(pdfReader, i);
            smartCopy.AddPage(copiedPage);
        }

        doc.Close();
    }
}