Scale PDF Objects in C#
IronPDF empowers developers to programmatically scale PDF objects, allowing for precise control over elements such as text and images within a PDF, without requiring modifications to the original file or the creation of an entirely new one.
Using the IronPDF library, you can easily scale PDF objects. The example below demonstrates how to accomplish this task with just a few lines of code.
5-Step Code to Scale PDF Objects
- string html = @"<img src='https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcTi8LuOR6_A98euPLs-JRwoLU7Nc31nVP15rw&s'>";
- PdfDocument pdf = renderer.RenderHtmlAsPdf(html);
- ImageObject image = pdf.Pages.First().ObjectModel.ImageObjects.First();
- image.Scale = new System.Drawing.PointF(0.7f, 0.7f);
- pdf.SaveAs("scaled_image.pdf");
Code Explanation
For this example, we first create an HTML string that includes an <img>
tag to embed an image. Afterwards, using the RenderHtmlAsPdf
method, we render that HTML string into a PdfDocument
object.
To access the ImageObject
that we just added, we navigate through the document's structure. We first access the PDF's initial page using Pages.First
. From there, we drill down into its ObjectModel
, which contains the structured content of the page. We then access the ImageObjects
collection, retrieve the first element, and assign it to a variable.
To scale the image, we assign a new PointF
to the Scale
property. In this example, we are scaling the image to 70% of its original size along both the x and y axes. Note that scaling by a factor greater than one increases the size, while a factor smaller than one (but greater than zero) effectively shrinks the image. You could also scale non-uniformly by providing different values for x and y.
After modifying the scale property, we finally call the SaveAs
method to save the PDF with the applied changes.
Discover How to Effortlessly Scale PDF DOM - Visit Our Guide Now!