How to resize an image before inserting it into the PDF document using C# and VB.NET
The Syncfusion Essential® PDF is a .NET PDF library used to create, read, and edit PDF documents. Using this library, you can resize an image before inserting it into the PDF document.
Steps to resize an image before inserting it into the PDF document
- Create a new C# console application project.
- Install the Syncfusion.Pdf.WinForms NuGet package as a reference to your .NET Framework application from NuGet.org.
- Include the following namespaces in Program.cs file.
C#
using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics; using System.Drawing; using System.Drawing.Drawing2D; using System.Drawing.Imaging;
VB.NET
Imports Syncfusion.Pdf Imports Syncfusion.Pdf.Graphics Imports System.Drawing Imports System.Drawing.Drawing2D Imports System.Drawing.Imaging
- Use the following code sample to resize an image before inserting it into the PDF document.
C#
//Create a new PDF document PdfDocument doc = new PdfDocument(); //Add a page to the document PdfPage page = doc.Pages.Add(); //Create PDF graphics for the page PdfGraphics graphics = page.Graphics; string imageFile = "../../Data/design.png"; string destinationFile = "../../Data/Resized_image.png"; //Resize image Image img = Image.FromFile(imageFile); ResizeImage(img, destinationFile, 100); //Load the image PdfBitmap image = new PdfBitmap(destinationFile); //Drawing image to the PDF page if (image.Height > page.Graphics.ClientSize.Height || image.Width > page.Graphics.ClientSize.Width) { page.Graphics.DrawImage(image, PointF.Empty, (page.GetClientSize())); } else { page.Graphics.DrawImage(image, new PointF(0, 0)); } //Save the document doc.Save("Output.pdf"); //Close the document doc.Close(true); //This will open the PDF file and the result will be seen in the default PDF Viewer Process.Start("Output.pdf");
Helper Methods:
/// <summary> /// Resize image /// </summary> /// <param name="image"></param> /// <param name="destinationPath"></param> /// <param name="percentage"></param> private void ResizeImage(Image image, string destinationPath, int percentage) { if (percentage < 0 || percentage > 100) throw new ArgumentOutOfRangeException("quality must be between 0 and 100."); //Encoder parameter for the image quality EncoderParameter qualityParam = new EncoderParameter(System.Drawing.Imaging.Encoder.Quality, percentage); //JPEG image codec ImageCodecInfo jpegCodec = GetEncoderInfo("image/jpeg"); EncoderParameters encoderParams = new EncoderParameters(1); encoderParams.Param[0] = qualityParam; Image img = Resize(image, 300, 300); //Save the resized image to the destination path img.Save(destinationPath, jpegCodec, encoderParams); } public Image Resize(Image image, int width, int height) { var res = new Bitmap(width, height); using (var graphic = Graphics.FromImage(res)) { graphic.InterpolationMode = InterpolationMode.HighQualityBicubic; graphic.SmoothingMode = SmoothingMode.HighQuality; graphic.PixelOffsetMode = PixelOffsetMode.HighQuality; graphic.CompositingQuality = CompositingQuality.HighQuality; graphic.DrawImage(image, 0, 0, width, height); } return res; } /// <summary> /// Returns the image codec with the given mime type /// </summary> private ImageCodecInfo GetEncoderInfo(string mimeType) { //Get image codecs for all image formats ImageCodecInfo[] codecs = ImageCodecInfo.GetImageEncoders(); //Find the correct image codec for (int i = 0; i < codecs.Length; i++) if (codecs[i].MimeType == mimeType) return codecs[i]; return null; }
VB.NET
'Create a new PDF document Dim doc As PdfDocument = New PdfDocument() 'Add a page to the document Dim page As PdfPage = doc.Pages.Add() 'Create PDF graphics for the page Dim graphics As PdfGraphics = page.Graphics Dim imageFile As String = "../../Data/design.png" Dim destinationFile As String = "../../Data/Resized_image.png" 'Resize image Dim img As Image = System.Drawing.Image.FromFile(imageFile) ResizeImage(img, destinationFile, 100) 'Load the image Dim image As PdfBitmap = New PdfBitmap(destinationFile) 'Draw image to the PDF page If image.Height > page.Graphics.ClientSize.Height OrElse image.Width > page.Graphics.ClientSize.Width Then page.Graphics.DrawImage(image, PointF.Empty, (page.GetClientSize())) Else page.Graphics.DrawImage(image, New PointF(0, 0)) End If 'Save the document doc.Save("Output.pdf") 'Close the document doc.Close(True) 'This will open the PDF file and the result will be seen in default PDF Viewer Process.Start("Output.pdf")
Helper Methods:
''' <summary> ''' Resize image ''' </summary> ''' <param name="image"></param> ''' <param name="destinationPath"></param> ''' <param name="percentage"></param> ''' <returns></returns> Private Function ResizeImage(ByVal image As Image, ByVal destinationPath As String, ByVal percentage As Integer) If percentage < 0 OrElse percentage > 100 Then Throw New ArgumentOutOfRangeException("quality must be between 0 and 100.") 'Encoder parameter for the image quality Dim qualityParam As EncoderParameter = New EncoderParameter(System.Drawing.Imaging.Encoder.Quality, percentage) 'JPEG image codec Dim jpegCodec As ImageCodecInfo = GetEncoderInfo("image/jpeg") Dim encoderParams As EncoderParameters = New EncoderParameters(1) encoderParams.Param(0) = qualityParam Dim img As Image = Resize(image, 300, 300) 'Save the resized image to the destination path img.Save(destinationPath, jpegCodec, encoderParams) End Function Public Function Resize(ByVal image As Image, ByVal width As Integer, ByVal height As Integer) As Image Dim res = New Bitmap(width, height) Using graphic = Graphics.FromImage(res) graphic.InterpolationMode = InterpolationMode.HighQualityBicubic graphic.SmoothingMode = SmoothingMode.HighQuality graphic.PixelOffsetMode = PixelOffsetMode.HighQuality graphic.CompositingQuality = CompositingQuality.HighQuality graphic.DrawImage(image, 0, 0, width, height) End Using Return res End Function ''' <summary> ''' Returns the image codec with the given mime type ''' </summary> ''' <param name="mimeType"></param> ''' <returns></returns> Private Function GetEncoderInfo(ByVal mimeType As String) As ImageCodecInfo 'Get image codecs for all image formats Dim codecs As ImageCodecInfo() = ImageCodecInfo.GetImageEncoders() 'Find the correct image codec For i As Integer = 0 To codecs.Length - 1 If codecs(i).MimeType = mimeType Then Return codecs(i) Next Return Nothing End Function
A Complete working sample can be download from ResizeImageSample.zip.
By executing the program, the image file size and dimension have been reduced and you will get the output document as follows,
i.e.,
Input image file | Output image file |
File size - 777KB | File size - 75KB |
Dimension – 550X836 | Dimension – 300X300 |
Take a moment to peruse the documentation. You can find the other options like inserting an image in a new and existing PDF document, inserting vector image, replacing images in an existing PDF document, Image pagination, applying transparency, and rotation to the image, convert multi-page TIFF to PDF.
Refer to here to explore a rich set of Syncfusion Essential® PDF features.
Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or the NuGet feed, include a license key in your product. Refer to the link to learn about generating and registering the Syncfusion® license key in your application to use the components without trail message.
See Also: