OilyAkara.WpfElementRenderer 1.0.2

dotnet add package OilyAkara.WpfElementRenderer --version 1.0.2
                    
NuGet\Install-Package OilyAkara.WpfElementRenderer -Version 1.0.2
                    
This command is intended to be used within the Package Manager Console in Visual Studio, as it uses the NuGet module's version of Install-Package.
<PackageReference Include="OilyAkara.WpfElementRenderer" Version="1.0.2" />
                    
For projects that support PackageReference, copy this XML node into the project file to reference the package.
<PackageVersion Include="OilyAkara.WpfElementRenderer" Version="1.0.2" />
                    
Directory.Packages.props
<PackageReference Include="OilyAkara.WpfElementRenderer" />
                    
Project file
For projects that support Central Package Management (CPM), copy this XML node into the solution Directory.Packages.props file to version the package.
paket add OilyAkara.WpfElementRenderer --version 1.0.2
                    
#r "nuget: OilyAkara.WpfElementRenderer, 1.0.2"
                    
#r directive can be used in F# Interactive and Polyglot Notebooks. Copy this into the interactive tool or source code of the script to reference the package.
#:package OilyAkara.WpfElementRenderer@1.0.2
                    
#:package directive can be used in C# file-based apps starting in .NET 10 preview 4. Copy this into a .cs file before any lines of code to reference the package.
#addin nuget:?package=OilyAkara.WpfElementRenderer&version=1.0.2
                    
Install as a Cake Addin
#tool nuget:?package=OilyAkara.WpfElementRenderer&version=1.0.2
                    
Install as a Cake Tool

WpfElementRenderer

A simple .NET library for WPF that renders any FrameworkElement into a high-quality, multi-page PDF or a series of paginated PNG images.

This library solves the common problem of exporting complex or dynamically sized WPF UI controls (like receipts, reports, or long forms) into a format suitable for printing or sharing. It automatically handles scaling to a standard A4 page width and splitting content across multiple pages, all while maintaining the correct aspect ratio.

Features

  • Render Any Element: Convert any FrameworkElement (e.g., Grid, StackPanel, UserControl) into a document.
  • Direct PDF Generation: Render a UI element directly to a multi-page PDF byte array in a single method call.
  • Paged Image Output: Optionally render to a list of PNG byte arrays for custom processing or print previews.
  • Automatic Pagination: Automatically calculates the number of pages needed based on the element's total height.
  • High-Quality Output: Renders at a configurable DPI (defaulting to 300 DPI for print quality).
  • Aspect-Ratio Correct Scaling: Uses a Viewbox to scale content uniformly to an A4 page width, preventing distortion.
  • Simple Static API: No need to instantiate objects; just call the static methods directly.

Installation

The library is available on NuGet. You can install it using the .NET CLI or the NuGet Package Manager Console.

.NET CLI
dotnet add package OilyAkara.WpfElementRenderer
Package Manager Console
Install-Package OilyAkara.WpfElementRenderer

Quick Start: Rendering to a PDF

This is the most common use case. The library handles everything in one step.

using System.IO;
using System.Windows;
using Microsoft.Win32;
using OilyAkara.WpfElementRenderer; // 1. Add the using directive

public partial class MyReportWindow : Window
{
    private void ExportToPdfButton_Click(object sender, RoutedEventArgs e)
    {
        // 2. IMPORTANT: Ensure the element has been measured and arranged.
        // If the element is not visible, you may need to force a layout pass.
        // For this example, 'PrintableContent' is a visible Grid in the window.
        
        // 3. Call the static method to generate the PDF bytes.
        byte[] pdfBytes = WpfElementRenderer.RenderToPdf(this.PrintableContent);

        // 4. Save the PDF to a file.
        var saveFileDialog = new SaveFileDialog
        {
            FileName = "Report.pdf",
            Filter = "PDF Document (*.pdf)|*.pdf"
        };

        if (saveFileDialog.ShowDialog() == true)
        {
            File.WriteAllBytes(saveFileDialog.FileName, pdfBytes);
            MessageBox.Show($"Successfully saved PDF to {saveFileDialog.FileName}", "Success");
        }
    }
}

Advanced: Rendering to PNG Pages

If you need more control, you can render the element to a list of PNG images first.

// (Inside your event handler, similar to the example above)

// Call the method to get a list of byte arrays, one for each page.
var imagePages = WpfElementRenderer.RenderToPngPages(this.PrintableContent);

// You can now process these images (e.g., save them, display them, etc.)
string desktopPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
for (int i = 0; i < imagePages.Count; i++)
{
    string filePath = Path.Combine(desktopPath, $"Report_Page_{i + 1}.png");
    File.WriteAllBytes(filePath, imagePages[i]);
}

MessageBox.Show($"{imagePages.Count} PNG page(s) saved to your desktop.");

API Reference

The library exposes its functionality through the static class WpfElementRenderer.

Methods

public static byte[] RenderToPdf(FrameworkElement element)

Renders a FrameworkElement directly to a multi-page PDF byte array. This is a convenience method that combines RenderToPngPages and CreatePdfFromPngPages.

  • element: The WPF FrameworkElement to be rendered.
  • Returns: A byte[] representing the complete PDF document.

public static List<byte[]> RenderToPngPages(FrameworkElement element, int dpi = 300)

Renders a FrameworkElement into a list of PNG byte arrays, where each array represents one A4 page.

  • element: The WPF FrameworkElement to be rendered.
  • dpi (optional): The resolution in dots-per-inch. Defaults to 300 for high quality.
  • Returns: A List<byte[]>, where each byte array contains the data for one PNG image page.

public static byte[] CreatePdfFromPngPages(List<byte[]> imagePages)

A utility method that combines a list of image byte arrays into a single PDF document.

  • imagePages: A list of byte arrays, where each item is an image (PNG is recommended).
  • Returns: A byte[] representing the generated PDF document.

How It Works

The library uses a multi-step process to achieve clean, paginated output:

  1. Scaling: The library internally wraps the provided FrameworkElement in a Viewbox, which is then constrained to the width of an A4 page. This scales the entire visual down uniformly.
  2. Measuring: The framework measures the total height of this newly scaled visual.
  3. Slicing: A VisualBrush is created from the scaled visual. This brush is then "painted" onto separate render targets, one for each page, using a calculated offset to create the "slices" for pagination.
  4. Encoding: Each rendered page is encoded as a PNG and returned as a byte array. For PDF output, these PNGs are then embedded into a PdfDocument.

Contributing

Contributions are welcome! If you find a bug or have a feature request, please open an issue. If you'd like to contribute code, please fork the repository and submit a pull request.

License

This project is licensed under the MIT License. See the LICENSE file for details.

Product Compatible and additional computed target framework versions.
.NET net8.0-windows7.0 is compatible.  net9.0-windows was computed.  net10.0-windows was computed. 
Compatible target framework(s)
Included target framework(s) (in package)
Learn more about Target Frameworks and .NET Standard.

NuGet packages

This package is not used by any NuGet packages.

GitHub repositories

This package is not used by any popular GitHub repositories.

Version Downloads Last Updated
1.0.2 215 10/23/2025

Version 1.0.2: Implemented element cloning to prevent the "logical child" runtime error when rendering visible UI elements.
Version 1.0.1: Corrected namespace and class structure for professional package consistency.
Version 1.0.0: Initial release.