Articles in this section
Category / Section

How to create a PDF table from ObservableCollection in UWP

5 mins read

Syncfusion Essential PDF is the UWP PDF library used to create, read, and edit PDF documents. Using this library, you can draw a table using ObservableCollection in a PDF document on the UWP platform.

Steps to draw the table using ObservableCollection in the PDF document programmatically:

  1. Create a new UWP application project. uwp-table
  2. Install the Syncfusion.Pdf.UWP NuGet package as a reference to your UWP applications from NuGet.org. uwp-table1
  3. In the MainPage.xaml, add a new button as follows.
    <Page
        x:Class="EuroSymbolSample.MainPage"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="using:EuroSymbolSample"
        xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
        mc:Ignorable="d"
        Background="{ThemeResource ApplicationPageBackgroundThemeBrush}">
     
        <Grid>
            <Button x:Name="btn1" Content="Generate PDF" Click="OnButtonClick" VerticalAlignment="Center" HorizontalAlignment="Center"></Button>
        </Grid>
    </Page>
    

 

  1. Include the following namespaces in the MainPage.xaml.cs file.
    using Syncfusion.Pdf;
    using Syncfusion.Pdf.Graphics;
    using Syncfusion.Pdf.Grid;
    

 

  1. Add a new class file in this UWP sample project, right-click the project and select Add -> Class and name it like Provider.cs. Add the following code snippet in the newly created Provider.cs class.
    internal sealed class Provider
    {
        /// <summary>
        /// Create the observable collection
        /// </summary>
        /// <returns></returns>
        internal static ObservableCollection<Adventure> GetProducts()
        {
            ObservableCollection<Adventure> AdventureCollection = new ObservableCollection<Adventure>();
            for (int i = 0; i < 10; i++)
            {
                Adventure adventureObj = new Adventure();
                adventureObj.CustomerID = "ERNSH";
                adventureObj.OrderID = i.ToString();
                adventureObj.ShipAddress = "Kirchgasse 6";
                adventureObj.ShipCity = "Graz";
                adventureObj.ShipCountry = "Austria";
                adventureObj.ShipName = "Ernst Handel";
                AdventureCollection.Add(adventureObj);
            }
            return AdventureCollection;
        }
    }

    /// <summary>
    /// Represents the customer details
    /// </summary>
    internal class Adventure
    {
        public string OrderID { get; set; }
        public string CustomerID { get; set; }
        public string ShipName { get; set; }
        public string ShipAddress { get; set; }
        public string ShipCity { get; set; }
        public string ShipCountry { get; set; }
    }

 

  1. Include the following code snippet in the click event of the button in MainPage.xaml.cs to draw the table to the PDF document using observable collection and save it in a stream.
    //Create a new PDF document
    PdfDocument doc = new PdfDocument();
     
    
    // Add a new PDF page
    PdfPage page = doc.Pages.Add();

    // Create the data source for the table
    ObservableCollection<Adventure> AdventureDetails = Provider.GetProducts();

    // Create a new PDF grid
    PdfGrid grid = new PdfGrid();

    // Add the data source
    grid.DataSource = AdventureDetails;

    // Apply built-in grid style
    grid.ApplyBuiltinStyle(PdfGridBuiltinStyle.GridTable6Colorful);

    // Create the layout format for the grid
    PdfGridLayoutFormat layoutFormat = new PdfGridLayoutFormat();

    // Set the layout type as paginate
    layoutFormat.Layout = PdfLayoutType.Paginate;

    // Draw the grid on the PDF page
    PdfGridLayoutResult gridResult = grid.Draw(page, new RectangleF(new PointF(0, 40), new SizeF(page.Graphics.ClientSize.Width, page.Graphics.ClientSize.Height - 100)), layoutFormat);

    MemoryStream stream = new MemoryStream();

    // Save the document
    doc.Save(stream);

    // Close the document
    doc.Close(true);

    // Save the PDF stream to a physical file
    Save(stream, "output.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.SetLength(0);
            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. uwp-table4

A complete working sample can be downloaded from TableSample.zip

Take a moment to peruse the documentation, where you can find other options like built-in table styles, cell customization, row customization, and table pagination to the 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&reg; assemblies from a trial setup or from the NuGet feed, include a license key in your projects. Refer to the link to learn about generating and registering the Syncfusion&reg; license key in your application to use the components without a trial message.

 

Conclusion

I hope you enjoyed learning about how to create a PDF table from ObservableCollection in UWP.

 

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