Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding white space in PDF using iTextSharp

Tags:

c#

itext

I have PDF where some of the text are very closed to the left and right border and I would like to add more white space at the border, top bottom left and right, for each pages in the PDF using iTextSharp.

Is this possible using iTextSharp or there is a better way?

like image 935
Steven Yong Avatar asked May 03 '26 22:05

Steven Yong


1 Answers

I managed to find the answer. The code below adjusts the size of the pages:

var inputPdf = new PdfReader(inputFile);   // Get input document

int pageCount = inputPdf.NumberOfPages;

if (end < start || end > pageCount)
    end = pageCount;

var inputDoc = new Document(inputPdf.GetPageSizeWithRotation(1)); 

using (var fs = new FileStream(outputFile, FileMode.Create))
{
    var outputWriter = PdfWriter.GetInstance(inputDoc, fs);
    inputDoc.Open();

    PdfContentByte cb1 = outputWriter.DirectContent;

    // Copy pages from input to output document
    for (int i = start; i <= end; i++)
    {
        var existingRec = inputPdf.GetPageSizeWithRotation(i);
        var newRec = new Rectangle(0.0f, 0.0f, existingRec.Width + 50, existingRec.Height + 25, 0);

        inputDoc.SetPageSize(newRec);
        inputDoc.NewPage();

        PdfImportedPage page = outputWriter.GetImportedPage(inputPdf, i);
        int rotation = inputPdf.GetPageRotation(i);

        if (rotation == 90 || rotation == 270)
             cb1.AddTemplate(page, 0, -1f, 1f, 0, 0, inputPdf.GetPageSizeWithRotation(i).Height);
        else cb1.AddTemplate(page, 1f, 0, 0, 1f, 25, 13); 
    }

    inputDoc.Close();
}

Hope this helps someone.

like image 189
Steven Yong Avatar answered May 05 '26 12:05

Steven Yong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!