Articles in this section
Category / Section

How to convert XAML to PDF in UWP?

3 mins read

Syncfusion Essential PDF is the UWP PDF library used to create, read, and edit PDF documents. Using this library, you can convert XAML to PDF in UWP platform.

Steps to convert XAML to PDF programmatically:

  1. Create a new UWP application project. Create new UWP blank application
  2. Install the Syncfusion.Pdf.UWP NuGet package as reference to your UWP application from NuGet.org Install required nuget packages
  3. Include the following namespaces in the MainPage.xaml.cs file.

C#

using Syncfusion.Pdf;
using Syncfusion.Pdf.Graphics;

 

  1. Include the following code snippet in the click event of the button in MainPage.xaml.cs to convert XAML to PDF and save it in a stream.

C#

//Create a new PDF document
PdfDocument document = new PdfDocument();
//Add a new page
PdfPage page = document.Pages.Add();
//Initialize render to bitmap
var logicalDpi = DisplayInformation.GetForCurrentView().LogicalDpi;
var renderTargetBitmap = new RenderTargetBitmap();
//Create a Bitmap from XAML page
await renderTargetBitmap.RenderAsync(SyncfusionForm);
var pixelBuffer = await renderTargetBitmap.GetPixelsAsync();
//Save the XAML in bitmap image
 using (var stream = new Windows.Storage.Streams.InMemoryRandomAccessStream())
{
        var encoder = await BitmapEncoder.CreateAsync(BitmapEncoder.JpegEncoderId, stream);
       encoder.SetPixelData(
       BitmapPixelFormat.Bgra8,
       BitmapAlphaMode.Ignore,
       (uint)renderTargetBitmap.PixelWidth,
       (uint)renderTargetBitmap.PixelHeight,
       logicalDpi,
       logicalDpi,
       pixelBuffer.ToArray());
      await encoder.FlushAsync();
      //Load and draw the bitmap image in PDF
      PdfImage img = PdfImage.FromStream(stream.AsStream());
      document.PageSettings.Margins.All = 0;
      if (img.Width > img.Height)                
           document.PageSettings.Orientation = PdfPageOrientation. Landscape;                
      else                
           document.PageSettings.Orientation = PdfPageOrientation. Portrait;                
      document.PageSettings.Size = new SizeF(img.Width, img.Height);                             
      PdfPage page = document.Pages.Add();
      page.Graphics.DrawImage(img, new RectangleF(0, 0, img.Width, img.Height));
}
//Save the document
MemoryStream docStream = new MemoryStream();
document.Save(docStream);
//Close the document 
document.Close(true);
Save(docStream, "Sample.pdf");

      

  1. Use the following helper method to save the stream as a physical file and open the file for viewing.
    #region Helper Methods
    public async void Save(Stream stream, string filename)
            {
                stream.Position = 0;
                StorageFile stFile;
                if (!(Windows.Foundation.Metadata.ApiInformation.IsTypePresent("Windows.Phone.UI.Input.HardwareButtons")))
                {
                    FileSavePicker savePicker = new FileSavePicker();
                    savePicker.DefaultFileExtension = ".pdf";
                    savePicker.SuggestedFileName = "Output";
                    savePicker.FileTypeChoices.Add("Adobe PDF Document", new List<string>() { ".pdf" });
                    stFile = await savePicker.PickSaveFileAsync();
                }
                else
                {
                    StorageFolder local = Windows.Storage.ApplicationData.Current.LocalFolder;
                    stFile = await local.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
                }
                if (stFile != null)
                {
                    Windows.Storage.Streams.IRandomAccessStream fileStream = await stFile.OpenAsync(FileAccessMode.ReadWrite);
                    Stream st = fileStream.AsStreamForWrite();
                    st.Write((stream as MemoryStream).ToArray(), 0, (int)stream.Length);
                    st.Flush();
                    st.Dispose();
                    fileStream.Dispose();
                    MessageDialog msgDialog = new MessageDialog("Do you want to view the Document?", "File created.");
                    UICommand yesCmd = new UICommand("Yes");
                    msgDialog.Commands.Add(yesCmd);
                    UICommand noCmd = new UICommand("No");
                    msgDialog.Commands.Add(noCmd);
                    IUICommand cmd = await msgDialog.ShowAsync();
                    if (cmd == yesCmd)
                    {
                        // Launch the retrieved file
                        bool success = await Windows.System.Launcher.LaunchFileAsync(stFile);
                    }
                }
            }
    #endregion
    

 

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

Screenshot of Output PDF document

A complete working sample can be downloaded from XAMLtoPDF_Sample.zip

Take a moment to peruse the documentation, where you will find other options like converting TIFF to PDF, RTF to PDF, and XPS to PDF document.

Refer here to explore the rich set of Syncfusion Essential PDF features.

Note:

Starting with v16.2.0.x, if you reference Syncfusion assemblies from trial setup or from the NuGet feed, include a license key in your projects. Refer to link to learn about generating and registering Syncfusion license key in your application to use the components without trail message.

 

Conclusion

I hope you enjoyed learning about how to convert XAML to PDF in UWP. 

You can refer to our   UWP PDF library’s feature tour page to know about its other groundbreaking feature representations. You can also explore our  UWP PDF library documentation to understand how to present and manipulate data. 

 

For current customers, you can check out our UWP from the License and Downloads page. If you are new to Syncfusion, you can try our 30-day free trial to check out our UWP PDF library and other UWP PDF components.

 

If you have any queries or require clarifications, please let us know in comments below. You can also contact us through our support forumsDirect-Trac, or feedback portal. We are always happy to assist you!

 

Did you find this information helpful?
Yes
No
Help us improve this page
Please provide feedback or comments
Comments
Please sign in to leave a comment
Access denied
Access denied