Rasterize a PDF page two ways: quick vs. full control

View as Markdown

BitmapGraphics ContainerPDFThumbnail

This sample compares the two ways to turn a PDF page into a bitmap. PdfFrame.GetBitmap is the quickest option, but it always returns a 24-bit RGB bitmap at the page's own resolution. Getting the page's vector content with GetContent and rasterizing it separately with GraphicsContainerRasterizer is slower, since rendering goes through the vector content rather than a ready-made bitmap, but it allows any target pixel format and resolution, such as an alpha-capable format at a higher DPI than the source page.

Code Snippet

using (var reader = new PdfReader("GraphicsContainer.pdf"))
{
    var frame = reader.Frames[0];

    // Quick: always 24-bit RGB, at the page's own resolution, with no control over
    // the output format -- but fast, since it comes straight from the frame.
    using (var quickBitmap = frame.GetBitmap())
    {
        quickBitmap.Save("RasterizedQuick.jpg");
    }

    // Full control: rendering the vector content separately is slower, but the target
    // pixel format and resolution are both configurable -- here, an alpha-capable format
    // at a higher resolution than the source page, which GetBitmap can't produce.
    using (var pageContent = frame.GetContent())
    {
        var rasterizer = new GraphicsContainerRasterizer(pageContent, PixelFormat.Format32bppArgb, RgbColor.Transparent)
        {
            TargetDpiX = 300f,
            TargetDpiY = 300f,
        };

        using (var customBitmap = rasterizer.Rasterize())
        {
            customBitmap.Save("RasterizedCustom.png");
        }
    }
}

Input

GraphicsContainer.pdf

Download

Output

RasterizedQuick.jpg

Download

RasterizedQuick.jpg

RasterizedQuick.jpg

RasterizedCustom.png

Download

RasterizedCustom.png

RasterizedCustom.png

Used APIs