Skip to main content

Example showing how to scale down the size (dimensions) of a PDF file using iTextSharp.

/// <remarks>Based on the shrinkpdf2 example at https://kb.itextpdf.com/home/it5kb/examples/scaling-and-rotating-pages</remarks>
public static byte[] ScaleDown(string sourceFile, float percentage = 0.90f)
{
    using (var outputStream = new MemoryStream())
    {
        using (var reader = new PdfReader(sourceFile))
        {
            using (var stamper = new PdfStamper(reader, outputStream))
            {
                var pages = reader.NumberOfPages;
                
                for (var page = 1; page <= pages; page++)
                {
                    var offsetX = (reader.GetPageSize(page).Width * (1 - percentage)) / 2;
                    var offsetY = (reader.GetPageSize(page).Height * (1 - percentage)) / 2;

                    stamper.GetUnderContent(page)
                        .SetLiteral(string.Format("\nq {0} 0 0 {1} {2} {3} cm\nq\n",
                            percentage.ToString(CultureInfo.CurrentCulture),
                            percentage.ToString(CultureInfo.CurrentCulture),
                            offsetX.ToString(CultureInfo.CurrentCulture),
                            offsetY.ToString(CultureInfo.CurrentCulture)));

                    stamper.GetOverContent(page).SetLiteral("\nQ\nQ\n");
                }
            }
        }

        return outputStream.ToArray();
    }
}