)
We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. (Last updated on: June 24, 2019).
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

How to convert XAML to PDF in UWP

Platform: UWP |
Control: Pdf |
Published Date: November 9, 2017 |
Last Revised Date: April 25, 2019
Tags: pdf, xaml, xamltopdf

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.

2X faster development

The ultimate UWP UI toolkit to boost your development speed.
ADD COMMENT
You must log in to leave a comment
Comments
Tushar Goyal Goyal
Mar 29, 2019

I replaced this line await renderTargetBitmap.RenderAsync(SyncfusionForm); with this await renderTargetBitmap.RenderAsync(new GenericManifestPDF(_manifestPDFDataModel));

It gives error in runtime that 'Value does not fall within the expected range'.

Reply
Gowthamraj Kumar [Syncfusion]
Mar 29, 2019

Hi Tushar,

We have checked the attached sample in our side, the XAML to PDF conversion works fine without any issue. We suspect this might be an issue with specific XAML code, so kindly provide us your XAML code to reproduce the issue in our side. It would more helpful for us to analyze further and assist you.

Regards, Gowthamraj K

Tushar Goyal Goyal
Mar 29, 2019

Hi Gowtham,

This is the XAML code of the page that I want to save in pdf format:

This is the code behind file of this page :

public GenericManifestPDF(ManifestPDFDataModel PDFDataModel) { this.InitializeComponent(); Function.Text = "Function :" + PDFDataModel.Function; Counts.Text = "Count :" + PDFDataModel.Counts; PrintedValue.Text = "Printed :" + PDFDataModel.CreationDate; RouteValue.Text = "Route :" + PDFDataModel.Route; BatchIDValue.Text = "Batch :" + PDFDataModel.BatchID; BatchBarcodeText.Text = "Batch Barcode :" + PDFDataModel.Barcode; IBarcodeWriter writer = new BarcodeWriter { Format = BarcodeFormat.CODE_39, Options = new ZXing.Common.EncodingOptions { Height = 100, Width = 450 } };

        var result = writer.Write(PDFDataModel.Barcode);
        BarcodeImage.Source = result;
        PDFItemsList.ItemsSource = PDFDataModel.ItemsPDFList;
    }

And I'm doing this is a separate VM class which gives error:

await renderTargetBitmap.RenderAsync(new GenericManifestPDF(_manifestPDFDataModel));

Tushar Goyal Goyal
Mar 29, 2019

I believe it didn't post xaml code so here it is:

Reply
Meikanda Nayanar [Syncfusion]
Apr 03, 2019

Hi Tushar,

We are checking your scenario about posting the XAML code from our end. In the meanwhile, can you send us the XAML code as a text file?

Thanks Meikandan

ragavan
Aug 01, 2020

Solution working for me. when I trying to export a larger XAML page ( height with 5000) PDF was not readable, Because added a big image into a single pdf page. How to split the image into multiple pages?

Reply
Gowthamraj Kumar [Syncfusion]
Aug 03, 2020

Hi Ragavan,

Thank you for your update.

Yes. We can allow you to split a large image to paginate across multiple pages in the PDF document by using PdfLayoutFormat class in our PDF library. We have checked the simple sample with a large XAMl page (5000 in height ) but is working properly. Please try the sample in your end and let us know the result.

Please refer the below links for more information,

UG: https://help.syncfusion.com/file-formats/pdf/working-with-images?cs-save-lang=1&cs-lang=uwp

KB: https://www.syncfusion.com/kb/9736/how-to-paginate-an-image-in-pdf-using-c-and-vb-net

Sample: https://www.syncfusion.com/downloads/support/directtrac/general/ze/XAMLtoPDF_Sample-740519264

If you are facing any issue, kindly provide more details such as complete code snippet, input image file, modified sample, product version to check the issue in our end. So, that it will be helpful for us to analyze and assist you further on this.

Regards,

Gowthamraj K

ragavan
Aug 04, 2020

@Gowthamraj

Seems you have shared again the old sample( XAML page not with 5000 height )

ragavan
Aug 05, 2020

Can you share with me the logic for split a large image to paginate across multiple pages in the PDF document?

given sample, I'm not able to find this part

Gowthamraj Kumar [Syncfusion]
Aug 05, 2020

Hi Ragavan,

We have already shared the updated sample with increasing the height of the XAML page up to (5000) and tried the XAML to PDF conversion in our end, but its working properly. It is not an old sample. We have shared the generated output document and screenshot for your reference. Please run the provided sample in your end and let us know the result.

Output : https://www.syncfusion.com/downloads/support/directtrac/general/ze/Document-844433976

Please screenshot for XAML page view and output document with highlighted the page size,

XAML Page view

Output Image

For Image pagination:

Please refer the below links for split a large image to paginate across multiple pages in the PDF document. When the image does not fit the layout size in that current page, it will move to next page of the PDF document. Please refer the KB and UG links more information,

UG: https://help.syncfusion.com/file-formats/pdf/working-with-images#image-pagination

KB: https://www.syncfusion.com/kb/9736/how-to-paginate-an-image-in-pdf-using-c-and-vb-net

If you are facing any issue, kindly provide more details such as complete code snippet, input image file, modified sample, product version to check the issue in our end. So, that it will be helpful for us to analyze and assist you further on this.

Regards,

Gowthamraj K

Please sign in to access our KB

This page will automatically be redirected to the sign-in page in 10 seconds.

Up arrow icon

Warning Icon You are using an outdated version of Internet Explorer that may not display all features of this and other websites. Upgrade to Internet Explorer 8 or newer for a better experience.Close Icon

Live Chat Icon For mobile
Live Chat Icon