Convert Word document to PDF in WinUI

23 Jul 20268 minutes to read

Syncfusion® DocIO is a .NET Word library used to create, read, edit, and convert Word documents programmatically without Microsoft Word or interop dependencies. Using this library, you can convert Word document to PDF in WinUI.

Prerequisites

  • Install the Windows App SDK extension for Visual Studio. For more details, refer here.
  • Supported environment: Visual Studio 2022 or later with the Windows App SDK workload on Windows 10 (build 17763 or later) or Windows 11.

WinUI Desktop app

Step 1: Create a new C# WinUI Desktop app. Select Blank App, Packaged with WAP (WinUI 3 in Desktop) from the template and click the Next button.

Create the WinUI Desktop app in Visual Studio

Step 2: Enter the project name and click Create button.

Create a project name for your new project

Step 3: Install Syncfusion.DocIORenderer.NET NuGet package as references to your WinUI Desktop application from the NuGet.org.

Syncfusion.DocIORenderer.NET NuGet package

NOTE

Starting with v16.2.0.x, if you reference Syncfusion® assemblies from trial setup or from the NuGet feed, you also have to add “Syncfusion.Licensing” assembly reference and include a license key in your projects. Please refer to this link to know about registering a Syncfusion® license key in your application to use our components.

Step 3a: Add the input Word document. In Solution Explorer, right-click the Assets folder, select Add > Existing Item, and add the Input.docx file. Select the file in Solution Explorer and set its Build Action to Embedded Resource in the Properties window so that the file can be loaded with GetManifestResourceStream in the next step.

Step 4: Add a new button to the MainWindow.xaml as shown below.

<Window
    x:Class="Convert_Word_Document_to_PDF.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    xmlns:local="using:Convert_Word_Document_to_PDF"
    xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
    xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
    mc:Ignorable="d">

    <StackPanel Orientation="Horizontal" HorizontalAlignment="Center" VerticalAlignment="Center">
        <Button x:Name="button" Click="ConvertWordtoPDF">Convert Word to PDF</Button>
    </StackPanel>
</Window>

Step 5: Include the following namespaces in the MainWindow.xaml.cs file.

using System.IO;
using System.Reflection;
using Microsoft.UI.Xaml;
using Microsoft.UI.Xaml.Controls;
using Syncfusion.DocIO.DLS;
using Syncfusion.DocIO;
using Syncfusion.DocIORenderer;
using Syncfusion.Pdf;

Step 6: Add a new async event handler ConvertWordtoPDF in MainWindow.xaml.cs and include the below code snippet to convert the Word document to PDF. The SaveHelper.SaveAndLaunch method used here is created in the next step.

//Loading an existing Word document
Assembly assembly = typeof(App).GetTypeInfo().Assembly;
using (WordDocument document = new WordDocument(assembly.GetManifestResourceStream("Convert_Word_Document_to_PDF.Assets.Input.docx"), FormatType.Docx))
{
    //Instantiation of DocIORenderer for Word to PDF conversion
    using (DocIORenderer render = new DocIORenderer())
    {
        //Converts Word document into PDF document
        using (PdfDocument pdfDocument = render.ConvertToPDF(document))
        {
            //Save a PDF document to the stream.
            using MemoryStream outputStream = new();
            pdfDocument.Save(outputStream);

            //Save the stream as a Word document file in the local machine.
            SaveHelper.SaveAndLaunch("Sample.pdf", outputStream);
        }
    }                                              
}

Save PDF document in WinUI

public static async void SaveAndLaunch(string filename, MemoryStream stream)
{
    StorageFile storageFile;
    string extension = Path.GetExtension(filename);
    //Gets process windows handle to open the dialog in application process.
    IntPtr windowHandle = System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle;
    if (!Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons"))
    {
        FileSavePicker savePicker = new();
        
        if (extension == ".pdf")
        {
            savePicker.DefaultFileExtension = ".pdf";
            savePicker.SuggestedFileName = filename;
            //Saves the file as Pdf file.
            savePicker.FileTypeChoices.Add("PDF", new List<string>() { ".pdf" });
        }

        WinRT.Interop.InitializeWithWindow.Initialize(savePicker, windowHandle);
        storageFile = await savePicker.PickSaveFileAsync();
    }
    else
    {
        StorageFolder local = ApplicationData.Current.LocalFolder;
        storageFile = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
    }
    if (storageFile != null)
    {
        using (IRandomAccessStream zipStream await storageFile.OpenAsync(FileAccessMode.ReadWrite))
        {
            //Writes compressed data from memory to file.
            using Stream outstream = zipStream.AsStreamForWrite();
            outstream.SetLength(0);
            byte[] buffer = stream.ToArray();
            outstream.Write(buffer, 0, buffer.Length);
            outstream.Flush();
        }

        //Creates message dialog box. 
        MessageDialog msgDialog = new("Do you want to view the Document?", "File has been converted successfully");
        UICommand yesCmd = new("Yes");
        msgDialog.Commands.Add(yesCmd);
        UICommand noCmd = new("No");
        msgDialog.Commands.Add(noCmd);

        WinRT.Interop.InitializeWithWindow.Initialize(msgDialog, windowHandle);

        //Showing a dialog box. 
        IUICommand cmd = await msgDialog.ShowAsync();
        if (cmd.Label == yesCmd.Label)
        {
            //Launch the saved file. 
            await Windows.System.Launcher.LaunchFileAsync(storageFile);
        }
    }
}

You can download a complete working sample from GitHub.

By executing the program, you will get the PDF document as follows.

Word to PDF in WinUI Desktop

Looking for the full .NET Word Library overview, features, pricing, and documentation? Visit the .NET Word Library page.

An online sample link to convert Word document to PDF in ASP.NET Core.