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. Image for the cookie policy date
Unfortunately, activation email could not send to your email. Please try again.
Syncfusion Feedback

How to convert HTML to PDF in UWP

Platform: UWP |
Control: Pdf |
Published Date: April 30, 2019 |
Last Revised Date: April 30, 2019

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 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 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.

create new uwp app.

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

Console App.

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

NuGet package.

  1. Copy the QtBinaries folder from the installed HtmltoPdfConverter package and paste it in the folder that contains the Desktop_ConsoleApp.csproj file.

Copy QtBinaries.

Paste QtBinaries.

  1. Include QtBinaries folder to the project and then set Copy to output directory to copy if newer to all the QtBinaries (All files including inner folders and files).

Include QtBinaries to the project.

Set copy local true to the QtBinaries.

  1. Include the following namespace and code snippet 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>
/// Creates the app service connection from 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>
/// Receives message from UWP app and sends a response back
/// </summary>
private static void Connection_RequestReceived(AppServiceConnection sender, AppServiceRequestReceivedEventArgs args)
{
string key = args.Request.Message.First().Key;
 
//Receive the URL from 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 the HTML to PDF converter 
HtmlToPdfConverter htmlConverter = new HtmlToPdfConverter(HtmlRenderingEngine.WebKit);
WebKitConverterSettings settings = new WebKitConverterSettings();
 
//Assign WebKit settings to HTML converter
htmlConverter.ConverterSettings = settings;
 
//Convert URL to PDF
PdfDocument document = htmlConverter.Convert(value);
 
MemoryStream stream = new MemoryStream();
 
//Save and close the PDF document 
document.Save(stream);
document.Close(true);
                
//Send the PDF document as 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 bin folder of the desktop application to AppX folder of the UWP application.

Copy the bin folder of desktop app to Appx folder.

Appx folder

  1. Add the following code snippet in 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 snippets in 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>
    /// Initializes 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 below 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 app service connection.
  2. Add the following code snippet in MainPage.xaml.cs to send request to desktop application with URL. The desktop application will return the response with PDF document.
    private async void Button_Click(object sender, RoutedEventArgs e)
    {
    ValueSet valueSet = new ValueSet();
    //Send request with 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 screenshot

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

UWP Desktop App: http://www.syncfusion.com/downloads/support/directtrac/general/ze/UwpApp_DesktopApp865988057

Note:

When creating a UWP App package, copy the QtBinaries folder from the Application installed folder to Application local cache folder. Then, send the Application local cache folder path to the desktop application with the request. So that, you can avoid the conversion failure due to restricted access permission. Refer to the following code snippet.

 

string InstalledPath = Path.Combine(Windows.ApplicationModel.Package.Current.InstalledLocation.Path, "QtBinaries");
string LocalCachePath = Path.Combine(ApplicationData.Current.LocalCacheFolder.Path, "QtBinaries");
 
//Copy the QtBinaries folder from installed location to LocalCache folder
if (!Directory.Exists(LocalCachePath) && !File.Exists(Path.Combine(LocalCachePath, "Syncfusion.WebKitWrapper.dll")))
{
//Now Create all of the directories
foreach (string dirPath in Directory.GetDirectories(InstalledPath, "*", SearchOption.AllDirectories))
Directory.CreateDirectory(dirPath.Replace(InstalledPath, LocalCachePath));
 
//Copy all the files & Replaces any files with the same name
foreach (string newPath in Directory.GetFiles(InstalledPath, "*.*", SearchOption.AllDirectories))
File.Copy(newPath, newPath.Replace(InstalledPath, LocalCachePath), true);
}
 
ValueSet valueSet = new ValueSet();
 
//Add URL to the request for converting HTML to PDF
valueSet.Add("request", "http://www.google.com");
 
//Add WebKitPath to the request from local folder
valueSet.Add("WebKitPath", LocalCachePath);
 
if (App.Connection != null)
{
//Send URL and WebKitPath from localcache folder to the windows Application using the App service connection.
AppServiceResponse response = await App.Connection.SendMessageAsync(valueSet);
 
string output = response.Message["response"] as string;
}

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.

2X faster development

The ultimate UWP UI toolkit to boost your development speed.
ADD COMMENT
You must log in to leave a comment
Comments
Tom
May 22, 2020

Great article on UWP bridging in general.

Reply

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