How to scale content of PDF

Shapes
2/6/2014

Downloads

This code sample creates a copy of a PDF document but the content in the output PDF is scaled.

C# code sample

1 using (FileStream inFile = new FileStream(@"..\..\input.pdf", FileMode.Open, FileAccess.Read)) 2 { 3 const double scale = 0.5; 4 5 // open the source document 6 Document documentIn = new Document(inFile); 7 8 // create the target document 9 Document documentOut = new Document(); 10 11 // enumerate the pages in the source document 12 for (int i = 0; i < documentIn.Pages.Count; i++) 13 { 14 Page inPage = documentIn.Pages[i]; 15 16 //append a page that has the SAME size as the original page 17 Page outPage = new Page(inPage.Width, inPage.Height); 18 documentOut.Pages.Add(outPage); 19 20 //calculate a new position for the content within the page 21 double left = (inPage.Width * (1 - scale)) / 2.0; 22 double bottom = (inPage.Height * (1 - scale)) / 2.0; 23 24 //calculate a new size of the content 25 double width = inPage.Width * scale; 26 double height = inPage.Height * scale; 27 28 //scale the box and translate it to the center of the page 29 PageShape pageShape = new PageShape(inPage, left, bottom, width, height); 30 31 outPage.VisualOverlay.Add(pageShape); 32 } 33 34 // write the target document to disk 35 using (FileStream outFile = new FileStream(@"..\..\output.pdf", FileMode.Create, FileAccess.Write)) 36 { 37 documentOut.Write(outFile); 38 } 39 }

VB.NET code sample

1 Using inFile As New FileStream("..\..\input.pdf", FileMode.Open, FileAccess.Read) 2 Const scale As Double = 0.5 3 4 ' open the source document 5 Dim documentIn As New Document(inFile) 6 7 ' create the target document 8 Dim documentOut As New Document() 9 10 ' enumerate the pages in the source document 11 For i As Integer = 0 To documentIn.Pages.Count - 1 12 Dim inPage As Page = documentIn.Pages(i) 13 14 'append a page that has the SAME size as the original page 15 Dim outPage As New Page(inPage.Width, inPage.Height) 16 documentOut.Pages.Add(outPage) 17 18 'calculate a new position for the content within the page 19 Dim left As Double = (inPage.Width * (1 - scale)) / 2.0 20 Dim bottom As Double = (inPage.Height * (1 - scale)) / 2.0 21 22 'calculate a new size of the content 23 Dim width As Double = inPage.Width * scale 24 Dim height As Double = inPage.Height * scale 25 26 'scale the box and translate it to the center of the page 27 Dim pageShape As New PageShape(inPage, left, bottom, width, height) 28 29 outPage.VisualOverlay.Add(pageShape) 30 Next 31 32 ' write the target document to disk 33 Using outFile As New FileStream("..\..\output.pdf", FileMode.Create, FileAccess.Write) 34 documentOut.Write(outFile) 35 End Using 36 End Using

Below you can see the screenshots of an original PDF and the output. Note that the size of the page remains the same while the content is scaled down.

Original PDF:

original_pdf.png

Scaled PDF:

scaled_pdf.png