Language: HTML | XAML

How to copy and paste HTML (XAML)

Applies to Windows only

Copying and pasting HTML content is different from other basic formats such as text or a link. The main challenge is that the content might contain references to other content. For example, it might contain img tags whose src attributes refer to locally-stored image files. When users copy this content, they expect to include both the text and the images. Apps that support copying and pasting HTML need to consider how to handle these references to ensure that users copy and paste the content they want.

To help you copy and paste HTML in a way that users expect, the Windows.ApplicationModel.DataTransfer namespace includes a few functions that help capture referenced elements, such as images. We'll show you how.

Check out our Clipboard sample app for comprehensive examples that show how to copy and paste other types of data.

What you need to know

Technologies

Prerequisites

  • You should be familiar with Quickstart: Clipboard basics.
  • You should be familiar with Visual Studio and its associated templates.
  • You should be familiar with C# development.
  • You should know how to identify HTML that the user has selected, and find instances of child elements like img tags within that selection.

Copying HTML to the Clipboard

  1. Prepare some HTML content for Clipboard operations.

    Use the HtmlFormatHelper.CreateHtmlFormat method to prepare the HTML content. This method adds the necessary headers and ensures that the HTML is formatted correctly for Clipboard operations.

    
    const string imgSrc = "ms-appx-web:///assets/windows-sdk.png";
    const string htmlFragment = "This sample shows how to copy HTML to the Clipboard. <br />"
            + "To <b>copy</b>, add text formats to a <i>DataPackage</i>, "
            + "and then pass <i>DataPackage</i> the to Clipboard.<br /> "
            + "To handle local image files (such as the one below), use "
            + "resourceMap collection."
            + "<br /><img id=\"scenario1LocalImage\" src=\""
            + imgSrc
            + "\" /><br />";
    
            string htmlFormat = HtmlFormatHelper.CreateHtmlFormat(htmlFragment);
    
    
  2. Create the DataPackage object.
    
    var dataPackage = new DataPackage();
    
    
  3. Add the HTML content to the DataPackage object.
    
    dataPackage.SetHtmlFormat(htmlFormat);
    
    
  4. Populate the resource map with content references.

    If the HTML contains references to other content, such as locally-stored image files, you need to add the references to the DataPackage.ResourceMap property. Here are the steps needed to add an image reference:

    1. Create a new Uri object to represent the local image file.
    2. Pass the Uri object to the RandomAccessStreamReference.CreateFromUri method to get a random-access stream reference for the local image file.
    3. Add the RandomAccessStreamReference to the DataPackage.ResourceMap property.
    
    
    // Populate the resource map with RandomAccessStreamReference objects 
    // corresponding to local image files embedded in the HTML.
    var imgUri = new Uri(imgSrc);
    var imgRef = RandomAccessStreamReference.CreateFromUri(imgUri);
    dataPackage.ResourceMap[imgSrc] = imgRef;
    
    
  5. Copy the content to the Clipboard.
    
    Clipboard.SetContent(dataPackage);
    
    

Pasting HTML from the Clipboard

  1. Get the contents of the clipboard.
    
    var dataPackageView = Clipboard.GetContent();
    
    
  2. Check whether the Clipboard contains HTML data.
    
    if (dataPackageView.Contains(StandardDataFormats.Html))
    {
        ...
    }
    
    
  3. If the Clipboard contains HTML, retrieve it and add it to your app as indicated by the user. The following example passes the HTML to a WebView control called OutputHtml.

    Caution  Be aware that HTML from another app is not trusted and you shouldn't display it unless you're sure the HTML doesn't have any dynamic content. Use the DataTransfer.HtmlFormatHelper.GetStaticFragment method to get shared HTML content without any dynamic elements such as script tags.

    
    string htmlFormat = null;
    try
    {
        htmlFormat = await dataPackageView.GetHtmlFormatAsync();
    }
    catch (Exception ex)
    {
        rootPage.NotifyUser("Error retrieving HTML format from Clipboard: " 
                + ex.Message, NotifyType.ErrorMessage);
    }
    
    if (htmlFormat != null)
    {
        string htmlFragment = HtmlFormatHelper.GetStaticFragment(htmlFormat);
        OutputHtml.NavigateToString("Html:<br/ > " + htmlFragment);
    }
    
    
  4. In the previous example, the WebView control parses and displays the HTML, including any referenced elements such as images specified by img tags. If you need to access referenced elements directly, you can get them from the DataPackage.ResourceMap property, as the following example shows.
    
    IReadOnlyDictionary<string, RandomAccessStreamReference> resMap = null;
    try
    {
        resMap = await dataPackageView.GetResourceMapAsync();
    }
    catch (Exception ex)
    {
        rootPage.NotifyUser("Error retrieving Resource map from Clipboard: " 
                + ex.Message, NotifyType.ErrorMessage);
    }
    
    if (resMap != null)
    {
        if (resMap.Count > 0)
        {
            foreach (var item in resMap)
            {
               OutputText.Text += Environment.NewLine + "Key: " + item.Key;
            }
        }
        else
        {
            OutputText.Text += Environment.NewLine + "Resource map is empty";
        }
    }
    
    

Complete examples

This example shows how to copy HTML with an embedded image to the Clipboard.


void copyHTML()
{
    // Prepare some HTML for copying to the Clipboard.
    const string imgSrc = "ms-appx-web:///assets/windows-sdk.png";
    const string htmlFragment = "This sample shows how to copy HTML to the "
            + "Clipboard. <br />"
            + "To <b>copy</b>, add text formats to a <i>DataPackage</i>, "
            + "and then pass <i>DataPackage</i> the to Clipboard.<br /> "
            + "To handle local image files (such as the one below), use "
            + "resourceMap collection."
            + "<br /><img id=\"scenario1LocalImage\" src=\""
            + imgSrc
            + "\" /><br />";

    string htmlFormat = HtmlFormatHelper.CreateHtmlFormat(htmlFragment);

    // Create a DataPackage object.
    var dataPackage = new DataPackage();

    // Set the content of the DataPackage as HTML format.
    dataPackage.SetHtmlFormat(htmlFormat);

    // Populate the resource map with RandomAccessStreamReference objects 
    // corresponding to local image files embedded in the HTML.
    var imgUri = new Uri(imgSrc);
    var imgRef = RandomAccessStreamReference.CreateFromUri(imgUri);
    dataPackage.ResourceMap[imgSrc] = imgRef;

    try
    {
        // Set the DataPackage to the clipboard.
        Clipboard.SetContent(dataPackage);
        OutputText.Text = "HTML format was copied to the Clipboard. ";
    }
    catch (Exception ex)
    {
        // Copying data to the Clipboard can fail if, another application is 
        // holding the Clipboard open.
        rootPage.NotifyUser("Error copying content to Clipboard: " +
            ex.Message + ". Try again", NotifyType.ErrorMessage);
    }
}

This example shows how to paste HTML from the Clipboard.


async void PasteHTML()
{
    var dataPackageView = Clipboard.GetContent();

    if (dataPackageView.Contains(StandardDataFormats.Html))
    {
        string htmlFormat = null;
        try
        {
            htmlFormat = await dataPackageView.GetHtmlFormatAsync();
        }
        catch (Exception ex)
        {
            rootPage.NotifyUser("Error retrieving HTML format from Clipboard: " + ex.Message, NotifyType.ErrorMessage);
        }

        if (htmlFormat != null)
        {
            string htmlFragment = HtmlFormatHelper.GetStaticFragment(htmlFormat);
            OutputHtml.NavigateToString("Html:<br/ > " + htmlFragment);
        }
    }
    else
    {
        OutputHtml.NavigateToString("Html:<br/ > No HTML format on clipboard");
    }
}

Related topics

Quickstart: Clipboard basics
Guidelines and checklist for clipboard commands
DataPackage
Windows.ApplicationModel.DataTransfer
Clipboard sample app

 

 

Show:
© 2014 Microsoft