Articles in this section
Category / Section

How to convert HTML to PDF in UWP

4 mins read

The Syncfusion HTML to PDF converter for .NET is used to convert webpages, SVG, MHTML, and HTML to PDF. Using this library, you can convert HTML to PDF in UWP using Desktop Bridging. Currently, the HTML to PDF converter is not compatible with the UWP platform. However, you can convert HTML to PDF in UWP by using two ways:

HTML to PDF conversion using desktop bridging:

  1. Create a desktop application, which will convert HTML to PDF.
  2. Launch and send the data to the desktop application from the UWP application.
  3. Get back the PDF document from the desktop application and save it from the UWP application.

Steps to convert HTML to PDF using desktop bridging:

  1. Create a new UWP application project.

Create UWP project.

  1. In configuration windows, name your project and select Next.

Name your project.

  1. Add a new desktop application to the same solution.

Add console application.

  1. In configuration windows, name your project and select Create.

 

Name your project.

  1. Install the Syncfusion.HtmlToPdfConverter.WinForms NuGet package as a reference to your desktop application from the NuGet.org.

Install NuGet package.

  1. Include the following namespace and code samples in desktop application.
     // [C# code]
    using System.Linq;
    using System.IO;
    using System.Threading;
    using Windows.ApplicationModel.AppService;
    using Windows.Foundation.Collections;
    using Syncfusion.Pdf;
    using Syncfusion.HtmlConverter;
    

 

class Program
{
static AppServiceConnection connection = null;
static void Main(string[] args)
{
Thread appServiceThread = new Thread(new ThreadStart(ThreadProc));
appServiceThread.Start();
Console.ForegroundColor = ConsoleColor.Yellow;
Console.WriteLine("**** Desktop console app ****");
Console.ReadLine();
}
 
/// <summary>
/// Create the app service connection from the UWP application.
/// </summary>
static async void ThreadProc()
{
connection = new AppServiceConnection();
connection.AppServiceName = "CommunicationService";
connection.PackageFamilyName = Windows.ApplicationModel.Package.Current.Id.FamilyName;
connection.RequestReceived += Connection_RequestReceived;
 
AppServiceConnectionStatus status = await connection.OpenAsync();
switch (status)
{
case AppServiceConnectionStatus.Success:
Console.WriteLine("Connection established - waiting for requests");
break;
case AppServiceConnectionStatus.AppNotInstalled:
Console.WriteLine("The app AppServicesProvider is not installed.");
return;
case AppServiceConnectionStatus.AppUnavailable:
Console.WriteLine("The app AppServicesProvider is not available.");
return;
case AppServiceConnectionStatus.AppServiceUnavailable:
Console.WriteLine(string.Format("The app AppServicesProvider is installed but it does not provide the app service {0}.", connection.AppServiceName));
return;
case AppServiceConnectionStatus.Unknown:
Console.WriteLine(string.Format("An unkown error occurred while we were trying to open an AppServiceConnection."));
return;
}
}
 
/// <summary>
/// Receive a message from the UWP app and send a response back.
/// </summary>
private static void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
{
string key = args.Request.Message.First().Key;
//Receive the URL from the request message and convert it to PDF.
string value = args.Request.Message.First().Value.ToString();
Console.WriteLine(string.Format("Received message '{0}' with value '{1}'", key, value));
 
if (key == "request")
{
ValueSet valueSet = new ValueSet();
 
//Initialize HTML to the PDF converter.
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter();
 
//Convert the URL to PDF.
PdfDocument document = htmlConverter.Convert(value);
 
//Save the document.
MemoryStream stream = new MemoryStream();
document.Save(stream);
document.Close(true);
                
//Send the PDF document as a response to the UWP app.
valueSet.Add("response", stream.ToArray());
 
Console.ForegroundColor = ConsoleColor.White;
Console.WriteLine("Sending the PDF document as response");
Console.WriteLine();
args.Request.SendResponseAsync(valueSet).Completed += delegate { };
}
}
}
  1. Build and copy the files and folder from the bin folder of the desktop application to the AppX folder of the UWP application.

Bin folder reference

Add reference in AppX folder.

  1. Add the following code samples in the MainPage.xaml.cs to launch the desktop application when initializing the UWP app.
    // [C# code]
    private async void LaunchDesktopAppAsync()
    {
    try
    {
    // Make sure the BackgroundProcess is in your AppX folder. If not, rebuild the solution.
    await Windows.ApplicationModel.FullTrustProcessLauncher.LaunchFullTrustProcessForCurrentAppAsync();
    }
    catch (Exception)
    {
    MessageDialog dialog = new MessageDialog("Rebuild the solution and make sure the BackgroundProcess is in your AppX folder");
    await dialog.ShowAsync();
    }
    }
    

code snippet.

  1. Add the following code samples in the App.xaml.cs to create an App service connection with the launched desktop application.
    // [C# code]
    public static AppServiceConnection Connection = null;
    BackgroundTaskDeferral appServiceDeferral = null;
     
    /// <summary>
    /// Initialize the app service on the host process. 
    /// </summary>
    protected override void OnBackgroundActivated(BackgroundActivatedEventArgs args)        
    {
    base.OnBackgroundActivated(args);
    if (args.TaskInstance.TriggerDetails is AppServiceTriggerDetails)
    {
    appServiceDeferral = args.TaskInstance.GetDeferral();                
    args.TaskInstance.Canceled += OnTaskCanceled; 
    // Associate a cancellation handler with the background task.                AppServiceTriggerDetails details = args.TaskInstance.TriggerDetails as AppServiceTriggerDetails;
    Connection = details.AppServiceConnection;
    }
    }
     
    /// <summary>
    /// Associate the cancellation handler with the background task. 
    /// </summary>
    private void OnTaskCanceled(IBackgroundTaskInstance sender, BackgroundTaskCancellationReason reason)
    {
    if (this.appServiceDeferral != null)
    {
    // Complete the service deferral.
    this.appServiceDeferral.Complete();
    }
    }
    

code snippet for app service connection.

  1. Update the package.appxmanifest file with following highlighted content.
    <?xml version="1.0" encoding="utf-8"?>
     
    <Package
      xmlns="http://schemas.microsoft.com/appx/manifest/foundation/windows10"
      xmlns:mp="http://schemas.microsoft.com/appx/2014/phone/manifest"
      xmlns:uap="http://schemas.microsoft.com/appx/manifest/uap/windows10"
      xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities" 
      xmlns:desktop="http://schemas.microsoft.com/appx/manifest/desktop/windows10" IgnorableNamespaces="uap mp rescap desktop">
      
     
      <Identity
        Name="4c39af9d-4c62-40ba-bf65-8e440b0a42b7"
        Publisher="CN=Prakash V"
        Version="1.0.0.0" />
     
       <mp:PhoneIdentity PhoneProductId="4c39af9d-4c62-40ba-bf65-8e440b0a42b7" PhonePublisherId="00000000-0000-0000-0000-000000000000"/>
     
      <Properties>
        <DisplayName>UwpApp</DisplayName>
        <PublisherDisplayName>Prakash V</PublisherDisplayName>
        <Logo>Assets\StoreLogo.png</Logo>
      </Properties>
     
      <Dependencies>
        <TargetDeviceFamily Name="Windows.Universal" MinVersion="10.0.0.0" MaxVersionTested="10.0.0.0" />
      </Dependencies>
     
      <Resources>
        <Resource Language="x-generate"/>
      </Resources>
     
      <Applications>
        <Application Id="App"
          Executable="$targetnametoken$.exe"
          EntryPoint="UwpApp.App">
          <uap:VisualElements
            DisplayName="UwpApp"
            Square150x150Logo="Assets\Square150x150Logo.png"
            Square44x44Logo="Assets\Square44x44Logo.png"
            Description="UwpApp"
            BackgroundColor="transparent">
           <uap:DefaultTile Wide310x150Logo="Assets\Wide310x150Logo.png"/>
            <uap:SplashScreen Image="Assets\SplashScreen.png" />
          </uap:VisualElements>
          <Extensions>
            <uap:Extension Category="windows.appService">
              <uap:AppService Name="CommunicationService" />
            </uap:Extension>
            <desktop:Extension Category="windows.fullTrustProcess" Executable="Desktop_ConsoleApp.exe" />
          </Extensions>
        </Application>
      </Applications>
     
      <Capabilities>
        <Capability Name="internetClient" />
        <rescap:Capability Name="runFullTrust" />
      </Capabilities>
    </Package>
    
  1. Now, run the UWP application. It will launch the desktop application and creates an app service connection.
  2. Add the following code sample in the MainPage.xaml.cs to send a request to the desktop application with the URL. The desktop application will return the response with a PDF document.
    private async void Button_Click(object sender, RoutedEventArgs e)
    {
    ValueSet valueSet = new ValueSet();
    //Send request with the URL.
    valueSet.Add("request", textBox.Text);
     
    if (App.Connection != null)
    {
    AppServiceResponse response = await App.Connection.SendMessageAsync(valueSet);
    var pdfData = response.Message["response"] as byte[];
    MemoryStream stream = new MemoryStream(pdfData);
    Save(stream, "Sample.pdf");
    }
    }
    

 

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 messageDialog = new MessageDialog("Do you want to view the Document?", "File created.");
UICommand yesCmd = new UICommand("Yes");
messageDialog.Commands.Add(yesCmd);
UICommand noCmd = new UICommand("No");
messageDialog.Commands.Add(noCmd);
IUICommand cmd = await messageDialog.ShowAsync();
if (cmd == yesCmd)
{
// Launch the retrieved file.
bool success = await Windows.System.Launcher.LaunchFileAsync(stFile);
}
}
}

By running the sample, you will get the output as follows.

Output.

The samples for converting HTML to PDF using a UWP desktop bridge connection are attached for your reference. Find the sample from the following link.

UWP Desktop App: UWPDesktopApp_Sample.zip

Take a moment to peruse the documentation for Converting HTML to PDF, where you will find various options for URL to PDF, HTML string to PDF, and Hyperlinks.

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

An online sample link to convert HTML to PDF.

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