PixelToNewDpi

ConvertUtil.PixelToNewDpi method

Converts pixels from one resolution to another.

public static int PixelToNewDpi(double pixels, double oldDpi, double newDpi)
ParameterTypeDescription
pixelsDoubleThe value to convert.
oldDpiDoubleThe current dpi (dots per inch) resolution.
newDpiDoubleThe new dpi (dots per inch) resolution.

Examples

Shows how to use convert points to pixels with default and custom resolution.

Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);

// Define the size of the top margin of this section in pixels, according to a custom DPI.
const double myDpi = 192;

PageSetup pageSetup = builder.PageSetup;
pageSetup.TopMargin = ConvertUtil.PixelToPoint(100, myDpi);

Assert.AreEqual(37.5d, pageSetup.TopMargin, 0.01d);

// At the default DPI of 96, a pixel is 0.75 points.
Assert.AreEqual(0.75d, ConvertUtil.PixelToPoint(1));

builder.Writeln($"This Text is {pageSetup.TopMargin} points/{ConvertUtil.PointToPixel(pageSetup.TopMargin, myDpi)} " +
                $"pixels (at a DPI of {myDpi}) from the top of the page.");

// Set a new DPI and adjust the top margin value accordingly.
const double newDpi = 300;
pageSetup.TopMargin = ConvertUtil.PixelToNewDpi(pageSetup.TopMargin, myDpi, newDpi);
Assert.AreEqual(59.0d, pageSetup.TopMargin, 0.01d);

builder.Writeln($"At a DPI of {newDpi}, the text is now {pageSetup.TopMargin} points/{ConvertUtil.PointToPixel(pageSetup.TopMargin, myDpi)} " +
                "pixels from the top of the page.");

doc.Save(ArtifactsDir + "UtilityClasses.PointsAndPixelsDpi.docx");

See Also