article

How to Export Presentations to HTML with Externally Linked Images inside .NET Apps

Email
Submitted on: 8/12/2015 9:07:25 AM
By: Sherazam  
Level: Intermediate
User Rating: Unrated
Compatibility: C#, VB.NET
Views: 2759
 
     This technical tip explains how .NET developers can export presentations to HTML with externally linked images inside their .NET applications. This article describes an advanced technique that allows controlling which resources are embedded into the resulting HTML file and which are saved externally and referenced from the HTML file. The default HTML export behavior is to embed any resource into the HTML file. Such approach results in a single HTML file that is easy to view and distribute. All necessary resources are base64-encoded inside. But such approach has two drawbacks. The size of output is significantly larger because of the base64 encoding.* It is difficult to replace the images contained in the file. In this article we will see how we can change the default behavior using the Aspose.Slides for .NET to link the images externally rather than embedding in the HTML file.

 
				This technical tip explains how .NET developers can export presentations to HTML with externally linked images inside their .NET applications. This article describes an advanced technique that allows controlling which resources are embedded into the resulting HTML file and which are saved externally and referenced from the HTML file. The default HTML export behavior is to embed any resource into the HTML file. Such approach results in a single HTML file that is easy to view and distribute. All necessary resources are base64-encoded inside. But such approach has two drawbacks. The size of output is significantly larger because of the base64 encoding.* It is difficult to replace the images contained in the file. In this article we will see how we can change the default behavior using the Aspose.Slides for .NET to link the images externally rather than embedding in the HTML file. We will use ILinkEmbedController interface which contains three methods to control the resource embedding and saving process. We can pass this interface to HtmlOptions class constructor when preparing the export. Following is the complete code of LinkController class which implements the ILinkEmbedController interface. As mentioned before, the LinkController must implement ILinkEmbedController interface.
// Code Snippet for Exporting Presentations to HTML with Externally Linked Images
//[C# Code Sample]
 
/// 
/// This class is responsible for making decisions about the resources saved externally.
/// It must implement the Aspose.Slides.Export.ILinkEmbedController interface.
/// 
class LinkController : ILinkEmbedController
{
	static LinkController()
	{
		s_templates.Add("image/jpeg", "image-{0}.jpg");
		s_templates.Add("image/png", "image-{0}.png");
	}
	/// 
	/// Default parameterless constructor
	/// 
	public LinkController()
	{
		m_externalImages = new Dictionary();
	}
	/// 
	/// Creates a class instance and sets the path where generated resource files will be saved to.
	/// 
	/// Path to the location where generated resource files will be stored.
	public LinkController(string savePath)
		:this()
	{
		SavePath = savePath;
	}
	/// 
	/// A ILinkEmbedController member
	/// 
	public LinkEmbedDecision GetObjectStoringLocation(int id, byte[] entityData, string semanticName,
		string contentType,
		string recomendedExtension)
	{
		// Here we make the decision about storing images externally.
		// The id is unique identifier of each object during the whole export operation.
		string template;
		// The s_templates dictionary contains content types we are going to store externally and the corresponding file name template.
		if (s_templates.TryGetValue(contentType, out template))
		{
			// Storing this resource to the export list
			m_externalImages.Add(id, template);
			return LinkEmbedDecision.Link;
		}
		// All other resources, if any, will be embedded
		return LinkEmbedDecision.Embed;
	}
	/// 
	/// A ILinkEmbedController member
	/// 
	public string GetUrl(int id, int referrer)
	{
		// Here we construct the resource reference string to form the tag: 
		// We need to check the dictionary to filter out unnecessary resources.
		// Along with checking we extract the corresponding file name template.
		string template;
		if (m_externalImages.TryGetValue(id, out template))
		{
			// Assuming we are going to store resource files just near the HTML file.
			// The image tag will look like  with the appropriate resource Id and extension.
			var fileUrl = String.Format(template, id);
			return fileUrl;
		}
		// null must be returned for the resources remaining embedded
		return null;
	}
	/// 
	/// A ILinkEmbedController member
	/// 
	public void SaveExternal(int id, byte[] entityData)
	{
		// Here we actually save the resource files to disk.
		// Once again, checking the dictionary. If the id is not found here it is a sign of an error in GetObjectStoringLocation or GetUrl methods.
		if (m_externalImages.ContainsKey(id))
		{
			// Now we use the file name stored in the dictionary and combine it with a path as required.
			// Constructing the file name using the stored template and the Id.
			var fileName = String.Format(m_externalImages[id], id);
			// Combining with the location directory
			var filePath = Path.Combine(SavePath ?? String.Empty, fileName);
			using (var fs = new FileStream(filePath, FileMode.Create))
				fs.Write(entityData, 0, entityData.Length);
		}
		else
			throw new Exception("Something is wrong");
	}
	/// 
	/// Gets or sets the path where generated resource files will be saved to.
	/// 
	public string SavePath { get; set; }
	/// 
	/// A dictionary to store associations between resource ids and corresponding file names.
	/// 
	private readonly Dictionary m_externalImages;
	/// 
	/// A dictionary to store associations between content types of resources we are going to store externally
	/// and corresponding file name templates.
	/// 
	private static readonly Dictionary s_templates = new Dictionary();
}
 
//[VB.NET Code Sample]
 
''' 
''' This class is responsible for making decisions about the resources saved externally.
''' It must implement the Aspose.Slides.Export.ILinkEmbedController interface.
''' 
Public Class LinkController
	Implements ILinkEmbedController
	Shared Sub New()
		s_templates.Add("image/jpeg", "image-{0}.jpg")
		s_templates.Add("image/png", "image-{0}.png")
	End Sub
	''' 
	''' Default parameterless constructor
	''' 
	Public Sub New()
		m_externalImages = New Dictionary(Of Integer, String)()
	End Sub
	''' 
	''' Creates a class instance and sets the path where generated resource files will be saved to.
	''' 
	''' Path to the location where generated resource files will be stored.
	Public Sub New(ByVal savePath As String)
		Me.New()
		Me.SavePath = savePath
	End Sub
	''' 
	''' A ILinkEmbedController member
	''' 
	Public Function GetObjectStoringLocation(ByVal id As Integer, ByVal entityData() As Byte, ByVal semanticName As String, ByVal contentType As String, ByVal recomendedExtension As String) As LinkEmbedDecision
		' Here we make the decision about storing images externally.
		' The id is unique identifier of each object during the whole export operation.
		Dim template As String
		' The s_templates dictionary contains content types we are going to store externally and the corresponding file name template.
		If s_templates.TryGetValue(contentType, template) Then
			' Storing this resource to the export list
			m_externalImages.Add(id, template)
			Return LinkEmbedDecision.Link
		End If
		' All other resources, if any, will be embedded
		Return LinkEmbedDecision.Embed
	End Function
	''' 
	''' A ILinkEmbedController member
	''' 
	Public Function GetUrl(ByVal id As Integer, ByVal referrer As Integer) As String
		' Here we construct the resource reference string to form the tag: 
		' We need to check the dictionary to filter out unnecessary resources.
		' Along with checking we extract the corresponding file name template.
		Dim template As String
		If m_externalImages.TryGetValue(id, template) Then
			' Assuming we are going to store resource files just near the HTML file.
			' The image tag will look like  with the appropriate resource Id and extension.
			Dim fileUrl = String.Format(template, id)
			Return fileUrl
		End If
		' null must be returned for the resources remaining embedded
		Return Nothing
	End Function
	''' 
	''' A ILinkEmbedController member
	''' 
	Public Sub SaveExternal(ByVal id As Integer, ByVal entityData() As Byte)
		' Here we actually save the resource files to disk.
		' Once again, checking the dictionary. If the id is not found here it is a sign of an error in GetObjectStoringLocation or GetUrl methods.
		If m_externalImages.ContainsKey(id) Then
			' Now we use the file name stored in the dictionary and combine it with a path as required.
			' Constructing the file name using the stored template and the Id.
			Dim fileName = String.Format(m_externalImages(id), id)
			' Combining with the location directory
			Dim filePath = Path.Combine(If((SavePath <> Nothing), SavePath, String.Empty), fileName)
			Using fs = New FileStream(filePath, FileMode.Create)
				fs.Write(entityData, 0, entityData.Length)
			End Using
		Else
			Throw New Exception("Something is wrong")
		End If
	End Sub
	''' 
	''' Gets or sets the path where generated resource files will be saved to.
	''' 
	Private privateSavePath As String
	Public Property SavePath() As String
		Get
			Return privateSavePath
		End Get
		Set(ByVal value As String)
			privateSavePath = value
		End Set
	End Property
	''' 
	''' A dictionary to store associations between resource ids and corresponding file names.
	''' 
	Private ReadOnly m_externalImages As Dictionary(Of Integer, String)
	''' 
	''' A dictionary to store associations between content types of resources we are going to store externally
	''' and corresponding file name templates.
	''' 
	Private Shared ReadOnly s_templates As Dictionary(Of String, String) = New Dictionary(Of String, String)()
End Class
After writing the LinkController class, now we will use it with HTMLOptions class to export the presentation to HTML having externally linked images using the following code.
//[VB.NET Code Sample]
using (var pres = new Presentation(@"C:\data\input.pptx"))
{
	var htmlOptions = new HtmlOptions(new LinkController(@"C:\data\out\"));
	htmlOptions.SlideImageFormat = SlideImageFormat.Svg(new SVGOptions());
	// This line is needed to remove the slide title display in HTML.
	// Comment it out if your prefer slide title displayed.
	htmlOptions.HtmlFormatter = HtmlFormatter.CreateDocumentFormatter(String.Empty, false);
	Console.WriteLine("Starting export");
	pres.Save(@"C:\data\out\output.html, SaveFormat.Html, htmlOptions);
}
//[VB.NET Code Sample]
Using pres = New Presentation("C:\data\input.pptx")
	Dim htmlOptions = New HtmlOptions(New LinkController("C:\data\out\"))
	htmlOptions.SlideImageFormat = SlideImageFormat.Svg(New SVGOptions())
	' This line is needed to remove the slide title display in HTML.
	' Comment it out if your prefer slide title displayed.
	htmlOptions.HtmlFormatter = HtmlFormatter.CreateDocumentFormatter(String.Empty, False)
	Console.WriteLine("Starting export")
	pres.Save("C:\data\out\output.html, SaveFormat.Html, htmlOptions);" & ControlChars.CrLf & "}

More about Aspose.Slides for .NET


Other 44 submission(s) by this author

 


Report Bad Submission
Use this form to tell us if this entry should be deleted (i.e contains no code, is a virus, etc.).
This submission should be removed because:

Your Vote

What do you think of this article (in the Intermediate category)?
(The article with your highest vote will win this month's coding contest!)
Excellent  Good  Average  Below Average  Poor (See voting log ...)
 

Other User Comments


 There are no comments on this submission.
 

Add Your Feedback
Your feedback will be posted below and an email sent to the author. Please remember that the author was kind enough to share this with you, so any criticisms must be stated politely, or they will be deleted. (For feedback not related to this particular article, please click here instead.)
 

To post feedback, first please login.