How to convert XAML to PDF in UWP?
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:
- Create a new UWP application project.
- Install the Syncfusion.Pdf.UWP NuGet package as reference to your UWP application from NuGet.org
- Include the following namespaces in the MainPage.xaml.cs file.
C#
using Syncfusion.Pdf; using Syncfusion.Pdf.Graphics;
- 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");
- 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.
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 the trial setup or the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering the Syncfusion® license key in your application to use the components without a trial message.
Conclusion:
I hope you enjoyed learning about how to convert XAML to PDF in UWP.
You can refer to our Flutter PDF feature tour page to learn about its other groundbreaking features and documentation, and how to quickly get started with configuration specifications. You can also explore our Flutter PDF Flutter PDF examples to understand how to create and manipulate data.
For current customers, you can check out our components from the License and Downloads page. If you are new to Syncfusion®, you can try our 30-day free trial to explore our other controls.
If you have any queries or require clarifications, please let us know in the comments section below. You can also contact us through our support forums or feedback portal. We are always happy to assist you!