Learn to use the NiPDF SDK

WPF Visual to PDF in 3 easy steps

This example show the 3 easy steps to go from a WPF Visual to a PDF file using the NiPDF Converter functionality. This is a great way to generate PDF files from .NET using Microsoft's WPF drawing APIs.

The following NiPDF function is used: NiXPS.Converter.XpsToPdf()

Source listing:

using System;
using System.Windows;
using System.Windows.Media;
using System.IO.Packaging;
using System.IO;
using System.Printing;
using System.Windows.Xps.Packaging;
using System.Windows.Xps;

partial class Test
{
    public static void example0001_GeneratePDF(string pIn, string pOut)
    {
        // STEP 1: Create or get a WPF Visual
        DrawingVisual visual = new DrawingVisual();
        {
            DrawingContext dc = visual.RenderOpen();
            Pen bluePen = new Pen(Brushes.Blue, 1);
            dc.DrawRectangle(Brushes.Yellow, bluePen, new Rect(10, 10, 800, 1000));
            Brush pinkBrush = new SolidColorBrush(Color.FromArgb(128, 255, 0, 255));
            Pen blackPen = new Pen(Brushes.Black, 1);
            dc.DrawEllipse(pinkBrush, blackPen, new Point(400, 500), 300, 200);
            dc.Close();
        }

        // STEP 2: Convert this WPF Visual to an XPS Document
        MemoryStream lMemoryStream = new MemoryStream();
        {
            Package package = Package.Open(lMemoryStream, FileMode.Create);
            XpsDocument doc = new XpsDocument(package);
            XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(doc);
            writer.Write(visual);
            doc.Close();
            package.Close();
        }

        // STEP 3: Convert this XPS Document to a PDF file
        MemoryStream lOutStream = new MemoryStream();
        NiXPS.Converter.XpsToPdf(lMemoryStream, lOutStream);
        File.WriteAllBytes(pOut, lOutStream.ToArray());
    }
}

(Required assembly references: NiPDF, PresentationCore, PresentationFramework, ReachFramework, System.Printing, WindowsBase.)