Skip to main content
Skip table of contents

Scaling and rotating pages

These examples were written in answer to questions such as:


rotate90degrees

JAVA

JAVA
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2023 Apryse Group NV
    Authors: Apryse Software.

    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
package com.itextpdf.samples.sandbox.stamper;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;

import java.io.File;

public class Rotate90Degrees {
    public static final String DEST = "./target/sandbox/stamper/rotate90degrees.pdf";
    public static final String SRC = "./src/main/resources/pdfs/pages.pdf";

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();

        new Rotate90Degrees().manipulatePdf(DEST);
    }

    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));

        for (int p = 1; p <= pdfDoc.getNumberOfPages(); p++) {
            PdfPage page = pdfDoc.getPage(p);
            int rotate = page.getRotation();
            if (rotate == 0) {
                page.setRotation(90);
            } else {
                page.setRotation((rotate + 90) % 360);
            }
        }

        pdfDoc.close();
    }
}

C#

C#
using System;
using System.IO;
using iText.Kernel.Pdf;

namespace iText.Samples.Sandbox.Stamper 
{
    public class Rotate90Degrees 
    {
        public static readonly String DEST = "results/sandbox/stamper/rotate90degrees.pdf";
        public static readonly String SRC = "../../../resources/pdfs/pages.pdf";

        public static void Main(String[] args) 
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
            
            new Rotate90Degrees().ManipulatePdf(DEST);
        }

        protected void ManipulatePdf(String dest) 
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
            
            for (int p = 1; p <= pdfDoc.GetNumberOfPages(); p++) 
            {
                PdfPage page = pdfDoc.GetPage(p);
                int rotate = page.GetRotation();
                if (rotate == 0) {
                    page.SetRotation(90);
                }
                else 
                {
                    page.SetRotation((rotate + 90) % 360);
                }
            }
            
            pdfDoc.Close();
        }
    }
}

scalerotate

JAVA

JAVA
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2023 Apryse Group NV
    Authors: Apryse Software.

    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
/**
 * <p>
 * Example that shows how to scale an existing PDF using the UserUnit and how to remove the rotation of a page.
 */

package com.itextpdf.samples.sandbox.stamper;

import com.itextpdf.kernel.pdf.PdfDictionary;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.kernel.pdf.PdfNumber;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;

import java.io.File;

public class ScaleRotate {
    public static final String DEST = "./target/sandbox/stamper/scale_rotate.pdf";
    public static final String SRC = "./src/main/resources/pdfs/pages.pdf";

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();

        new ScaleRotate().manipulatePdf(DEST);
    }

    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));

        for (int p = 1; p <= pdfDoc.getNumberOfPages(); p++) {
            PdfDictionary page = pdfDoc.getPage(p).getPdfObject();
            if (page.getAsNumber(PdfName.UserUnit) == null) {
                page.put(PdfName.UserUnit, new PdfNumber(2.5f));
            }
            page.remove(PdfName.Rotate);
        }

        pdfDoc.close();
    }
}

C#

C#
using System;
using System.IO;
using iText.Kernel.Pdf;

namespace iText.Samples.Sandbox.Stamper 
{
    public class ScaleRotate 
    {
        public static readonly String DEST = "results/sandbox/stamper/scale_rotate.pdf";
        public static readonly String SRC = "../../../resources/pdfs/pages.pdf";

        public static void Main(String[] args) 
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
            
            new ScaleRotate().ManipulatePdf(DEST);
        }

        protected void ManipulatePdf(String dest) 
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
            
            for (int p = 1; p <= pdfDoc.GetNumberOfPages(); p++) 
            {
                PdfDictionary page = pdfDoc.GetPage(p).GetPdfObject();
                if (page.GetAsNumber(PdfName.UserUnit) == null) 
                {
                    page.Put(PdfName.UserUnit, new PdfNumber(2.5f));
                }
                page.Remove(PdfName.Rotate);
            }
            
            pdfDoc.Close();
        }
    }
}

shrinkpdf

JAVA

JAVA
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2023 Apryse Group NV
    Authors: Apryse Software.

    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
package com.itextpdf.samples.sandbox.stamper;

import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfResources;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;

import java.io.File;

public class ShrinkPdf {
    public static final String DEST = "./target/sandbox/stamper/shrink_pdf.pdf";
    public static final String SRC = "./src/main/resources/pdfs/hero.pdf";

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();

        new ShrinkPdf().manipulatePdf(DEST);
    }

    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));

        for (int p = 1; p <= pdfDoc.getNumberOfPages(); p++) {
            PdfPage page = pdfDoc.getPage(p);
            Rectangle media = page.getCropBox();
            if (media == null) {
                media = page.getMediaBox();
            }

            // Shrink the page to 50%
            Rectangle crop = new Rectangle(0, 0, media.getWidth() / 2, media.getHeight() / 2);
            page.setMediaBox(crop);
            page.setCropBox(crop);

            // The content, placed on a content stream before, will be rendered before the other content
            // and, therefore, could be understood as a background (bottom "layer")
            new PdfCanvas(page.newContentStreamBefore(),
                    page.getResources(), pdfDoc).writeLiteral("\nq 0.5 0 0 0.5 0 0 cm\nq\n");

            // The content, placed on a content stream after, will be rendered after the other content
            // and, therefore, could be understood as a foreground (top "layer")
            new PdfCanvas(page.newContentStreamAfter(),
                    page.getResources(), pdfDoc).writeLiteral("\nQ\nQ\n");
        }

        pdfDoc.close();
    }
}

C#

C#
using System;
using System.IO;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;

namespace iText.Samples.Sandbox.Stamper 
{
    public class ShrinkPdf 
    {
        public static readonly String DEST = "results/sandbox/stamper/shrink_pdf.pdf";
        public static readonly String SRC = "../../../resources/pdfs/hero.pdf";

        public static void Main(String[] args) 
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
            
            new ShrinkPdf().ManipulatePdf(DEST);
        }

        protected void ManipulatePdf(String dest) 
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
            
            for (int p = 1; p <= pdfDoc.GetNumberOfPages(); p++) 
            {
                PdfPage page = pdfDoc.GetPage(p);
                Rectangle media = page.GetCropBox();
                if (media == null) 
                {
                    media = page.GetMediaBox();
                }
                
                // Shrink the page to 50%
                Rectangle crop = new Rectangle(0, 0, media.GetWidth() / 2, media.GetHeight() / 2);
                page.SetMediaBox(crop);
                page.SetCropBox(crop);
                
                // The content, placed on a content stream before, will be rendered before the other content
                // and, therefore, could be understood as a background (bottom "layer")
                new PdfCanvas(page.NewContentStreamBefore(), 
                        page.GetResources(), pdfDoc).WriteLiteral("\nq 0.5 0 0 0.5 0 0 cm\nq\n");
                
                // The content, placed on a content stream after, will be rendered after the other content
                // and, therefore, could be understood as a foreground (top "layer")
                new PdfCanvas(page.NewContentStreamAfter(),
                        page.GetResources(), pdfDoc).WriteLiteral("\nQ\nQ\n");
            }
            
            pdfDoc.Close();
        }
    }
}

shrinkpdf2

JAVA

JAVA
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2023 Apryse Group NV
    Authors: Apryse Software.

    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
package com.itextpdf.samples.sandbox.stamper;

import com.itextpdf.kernel.geom.Rectangle;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;

import java.io.File;
import java.util.Locale;

public class ShrinkPdf2 {
    public static final String DEST = "./target/sandbox/stamper/shrink_pdf2.pdf";
    public static final String SRC = "./src/main/resources/pdfs/hero.pdf";

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();

        new ShrinkPdf2().manipulatePdf(DEST);
    }

    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));

        // Please note that we don't change the page size in this example, but only shrink the content (in this case to 80%)
        // and the content is shrunk to center of the page, leaving bigger margins to the top, bottom, left and right
        float percentage = 0.8f;
        for (int p = 1; p <= pdfDoc.getNumberOfPages(); p++) {
            PdfPage pdfPage = pdfDoc.getPage(p);
            Rectangle pageSize = pdfPage.getPageSize();

            // Applying the scaling in both X, Y direction to preserve the aspect ratio.
            float offsetX = (pageSize.getWidth() * (1 - percentage)) / 2;
            float offsetY = (pageSize.getHeight() * (1 - percentage)) / 2;

            // The content, placed on a content stream before, will be rendered before the other content
            // and, therefore, could be understood as a background (bottom "layer")
            new PdfCanvas(pdfPage.newContentStreamBefore(), pdfPage.getResources(), pdfDoc)
                    .writeLiteral(String.format(Locale.ENGLISH, "\nq %s 0 0 %s %s %s cm\nq\n",
                            percentage, percentage, offsetX, offsetY));

            // The content, placed on a content stream after, will be rendered after the other content
            // and, therefore, could be understood as a foreground (top "layer")
            new PdfCanvas(pdfPage.newContentStreamAfter(), pdfPage.getResources(), pdfDoc)
                    .writeLiteral("\nQ\nQ\n");
        }

        pdfDoc.close();
    }
}

C#

C#
using System;
using System.IO;
using iText.Kernel.Geom;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;

namespace iText.Samples.Sandbox.Stamper 
{
    public class ShrinkPdf2 
    {
        public static readonly String DEST = "results/sandbox/stamper/shrink_pdf2.pdf";
        public static readonly String SRC = "../../../resources/pdfs/hero.pdf";

        public static void Main(String[] args) 
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();
            
            new ShrinkPdf2().ManipulatePdf(DEST);
        }

        protected void ManipulatePdf(String dest) 
        {
            PdfDocument pdfDoc = new PdfDocument(new PdfReader(SRC), new PdfWriter(dest));
            
            // Please note that we don't change the page size in this example, but only shrink the content (in this case to 80%)
            // and the content is shrunk to center of the page, leaving bigger margins to the top, bottom, left and right
            float percentage = 0.8f;
            for (int p = 1; p <= pdfDoc.GetNumberOfPages(); p++) 
            {
                PdfPage pdfPage = pdfDoc.GetPage(p);
                Rectangle pageSize = pdfPage.GetPageSize();
                
                // Applying the scaling in both X, Y direction to preserve the aspect ratio.
                float offsetX = (pageSize.GetWidth() * (1 - percentage)) / 2;
                float offsetY = (pageSize.GetHeight() * (1 - percentage)) / 2;
                
                // The content, placed on a content stream before, will be rendered before the other content
                // and, therefore, could be understood as a background (bottom "layer")
                new PdfCanvas(pdfPage.NewContentStreamBefore(), pdfPage.GetResources(), pdfDoc)
                        .WriteLiteral(String.Format(System.Globalization.CultureInfo.InvariantCulture, 
                                "\nq {0:f} 0 0 {1:f} {2:f} {3:f} cm\nq\n", percentage, percentage, offsetX, offsetY));
                
                // The content, placed on a content stream after, will be rendered after the other content
                // and, therefore, could be understood as a foreground (top "layer")
                new PdfCanvas(pdfPage.NewContentStreamAfter(), pdfPage.GetResources(), pdfDoc).WriteLiteral("\nQ\nQ\n");
            }
            
            pdfDoc.Close();
        }
    }
}

scaledown

JAVA

JAVA
/*
    This file is part of the iText (R) project.
    Copyright (c) 1998-2023 Apryse Group NV
    Authors: Apryse Software.

    For more information, please contact iText Software at this address:
    sales@itextpdf.com
 */
package com.itextpdf.samples.sandbox.events;

import com.itextpdf.kernel.events.Event;
import com.itextpdf.kernel.events.IEventHandler;
import com.itextpdf.kernel.events.PdfDocumentEvent;
import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfName;
import com.itextpdf.kernel.pdf.PdfNumber;
import com.itextpdf.kernel.pdf.PdfWriter;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.kernel.pdf.PdfDictionary;
import com.itextpdf.kernel.pdf.PdfPage;
import com.itextpdf.kernel.pdf.PdfArray;
import com.itextpdf.kernel.pdf.canvas.PdfCanvas;
import com.itextpdf.kernel.pdf.xobject.PdfFormXObject;

import java.io.File;

public class ScaleDown {
    public static final String DEST = "./target/sandbox/events/scale_down.pdf";

    public static final String SRC = "./src/main/resources/pdfs/orientations.pdf";

    public static void main(String[] args) throws Exception {
        File file = new File(DEST);
        file.getParentFile().mkdirs();

        new ScaleDown().manipulatePdf(DEST);
    }

    protected void manipulatePdf(String dest) throws Exception {
        PdfDocument srcDoc = new PdfDocument(new PdfReader(SRC));
        PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));

        float scale = 0.5f;
        ScaleDownEventHandler eventHandler = new ScaleDownEventHandler(scale);
        pdfDoc.addEventHandler(PdfDocumentEvent.START_PAGE, eventHandler);

        int numberOfPages = srcDoc.getNumberOfPages();
        for (int p = 1; p <= numberOfPages; p++) {
            eventHandler.setPageDict(srcDoc.getPage(p).getPdfObject());

            // Copy and paste scaled page content as formXObject
            PdfFormXObject page = srcDoc.getPage(p).copyAsFormXObject(pdfDoc);
            PdfCanvas canvas = new PdfCanvas(pdfDoc.addNewPage());
            canvas.addXObjectWithTransformationMatrix(page, scale, 0f, 0f, scale, 0f, 0f);
        }

        pdfDoc.close();
        srcDoc.close();
    }


    private static class ScaleDownEventHandler implements IEventHandler {
        protected float scale = 1;
        protected PdfDictionary pageDict;

        public ScaleDownEventHandler(float scale) {
            this.scale = scale;
        }

        public void setPageDict(PdfDictionary pageDict) {
            this.pageDict = pageDict;
        }

        @Override
        public void handleEvent(Event currentEvent) {
            PdfDocumentEvent docEvent = (PdfDocumentEvent) currentEvent;
            PdfPage page = docEvent.getPage();

            page.put(PdfName.Rotate, pageDict.getAsNumber(PdfName.Rotate));

            // The MediaBox value defines the full size of the page.
            scaleDown(page, pageDict, PdfName.MediaBox, scale);

            // The CropBox value defines the visible size of the page.
            scaleDown(page, pageDict, PdfName.CropBox, scale);
        }

        protected void scaleDown(PdfPage destPage, PdfDictionary pageDictSrc, PdfName box, float scale) {
            PdfArray original = pageDictSrc.getAsArray(box);
            if (original != null) {
                float width = original.getAsNumber(2).floatValue() - original.getAsNumber(0).floatValue();
                float height = original.getAsNumber(3).floatValue() - original.getAsNumber(1).floatValue();

                PdfArray result = new PdfArray();
                result.add(new PdfNumber(0));
                result.add(new PdfNumber(0));
                result.add(new PdfNumber(width * scale));
                result.add(new PdfNumber(height * scale));
                destPage.put(box, result);
            }
        }
    }
}

C#

C#
using System;
using System.IO;
using iText.Kernel.Events;
using iText.Kernel.Pdf;
using iText.Kernel.Pdf.Canvas;
using iText.Kernel.Pdf.Xobject;

namespace iText.Samples.Sandbox.Events
{
    public class ScaleDown
    {
        public static readonly String DEST = "results/sandbox/events/scale_down.pdf";

        public static readonly String SRC = "../../../resources/pdfs/orientations.pdf";

        public static void Main(String[] args)
        {
            FileInfo file = new FileInfo(DEST);
            file.Directory.Create();

            new ScaleDown().ManipulatePdf(DEST);
        }

        protected void ManipulatePdf(String dest)
        {
            PdfDocument srcDoc = new PdfDocument(new PdfReader(SRC));
            PdfDocument pdfDoc = new PdfDocument(new PdfWriter(dest));

            float scale = 0.5f;
            ScaleDownEventHandler eventHandler = new ScaleDownEventHandler(scale);
            pdfDoc.AddEventHandler(PdfDocumentEvent.START_PAGE, eventHandler);

            int numberOfPages = srcDoc.GetNumberOfPages();
            for (int p = 1; p <= numberOfPages; p++)
            {
                eventHandler.SetPageDict(srcDoc.GetPage(p).GetPdfObject());

                // Copy and paste scaled page content as formXObject
                PdfFormXObject page = srcDoc.GetPage(p).CopyAsFormXObject(pdfDoc);
                PdfCanvas canvas = new PdfCanvas(pdfDoc.AddNewPage());
                canvas.AddXObjectWithTransformationMatrix(page, scale, 0f, 0f, scale, 0f, 0f);
            }

            pdfDoc.Close();
            srcDoc.Close();
        }

        private class ScaleDownEventHandler : IEventHandler
        {
            protected float scale = 1;
            protected PdfDictionary pageDict;

            public ScaleDownEventHandler(float scale)
            {
                this.scale = scale;
            }

            public void SetPageDict(PdfDictionary pageDict)
            {
                this.pageDict = pageDict;
            }

            public void HandleEvent(Event currentEvent)
            {
                PdfDocumentEvent docEvent = (PdfDocumentEvent) currentEvent;
                PdfPage page = docEvent.GetPage();

                page.Put(PdfName.Rotate, pageDict.GetAsNumber(PdfName.Rotate));

                // The MediaBox value defines the full size of the page.
                ScaleDown(page, pageDict, PdfName.MediaBox, scale);

                // The CropBox value defines the visible size of the page.
                ScaleDown(page, pageDict, PdfName.CropBox, scale);
            }

            protected void ScaleDown(PdfPage destPage, PdfDictionary pageDictSrc, PdfName box, float scale)
            {
                PdfArray original = pageDictSrc.GetAsArray(box);
                if (original != null)
                {
                    float width = original.GetAsNumber(2).FloatValue() - original.GetAsNumber(0).FloatValue();
                    float height = original.GetAsNumber(3).FloatValue() - original.GetAsNumber(1).FloatValue();

                    PdfArray result = new PdfArray();
                    result.Add(new PdfNumber(0));
                    result.Add(new PdfNumber(0));
                    result.Add(new PdfNumber(width * scale));
                    result.Add(new PdfNumber(height * scale));
                    destPage.Put(box, result);
                }
            }
        }
    }
}
JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.