LinkedIn

Friday, April 8, 2011

Rendering a document file from a document library on web part in HTML format

The following is the code for rendering a document file in a document library in sharepoint as html file in a iFrame in a web part. This will be very userfull if you want to render a document in readonly mode on browser.
string url = SPAccessLayer.DownloadAndConvertFile(url of document in the document library);


string name = "QueryStringPageViewer_" + this.UniqueID;

output.AddAttribute(HtmlTextWriterAttribute.Id, name, false);

output.AddAttribute(HtmlTextWriterAttribute.Name, name, false);

output.AddAttribute(HtmlTextWriterAttribute.Width, "100%", false);

output.AddAttribute(HtmlTextWriterAttribute.Height, "60%", false);

output.AddAttribute(HtmlTextWriterAttribute.Height, "60%", false);

output.AddAttribute(HtmlTextWriterAttribute.Src, url, false);

output.AddAttribute("ddf_src", url, false);

output.AddAttribute("frameBorder", "0", false);

output.RenderBeginTag(HtmlTextWriterTag.Iframe);

output.RenderBeginTag(HtmlTextWriterTag.Div);

output.Write("IFrames not supported by this browser");

output.RenderEndTag();

output.RenderEndTag();


SPAccessLayer.cs:

public static string DownloadAndConvertFile( string itemUrl)
{
string DestFile = string.Empty;
string DestHtmlFile = string.Empty;
string listFileName = string.Empty;
string pDestFilePath = @"C:\Inetpub\wwwroot\wss\VirtualDirectories\4568\Doc";
string pDestHtmlPath = @"C:\Inetpub\wwwroot\wss\VirtualDirectories\4568\HTML";
string DestinationHTMLFilePath = ConfigurationSettings.AppSettings["DestinationHTMLFilePath"];
string DocumentDownloadedPath = ConfigurationSettings.AppSettings["DocumentDownloadedPath"];
pDestFilePath = DocumentDownloadedPath;
pDestHtmlPath = DestinationHTMLFilePath;
SPListItem aItem = SPContext.Current.Web.GetListItem(itemUrl);
if (aItem != null)
{
listFileName = aItem["FileLeafRef"].ToString();
if (listFileName.ToUpper().EndsWith("X"))
listFileName = listFileName.Substring(0, listFileName.Length - 1);
byte[] byteFile = aItem.File.OpenBinary();

//HttpContext.Current.Response.Write(DestFile);


if (listFileName.Contains(".doc"))
{
DestFile = pDestFilePath + listFileName;
FileStream fStream = File.Create(DestFile);
fStream.Write(byteFile, 0, byteFile.Length);
fStream.Close();
DestHtmlFile = OfficeUtility.ConvertWordToHTML(listFileName, pDestFilePath, pDestHtmlPath);
}
else
{
DestFile = @"C:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS\MetropolisDocuments\HTMLFiles\" + listFileName;
FileStream fStream = File.Create(DestFile);
fStream.Write(byteFile, 0, byteFile.Length);
fStream.Close();
DestHtmlFile = listFileName;
}
}
//HttpContext.Current.Response.Write(DestHtmlFile);
return pDestHtmlPath + DestHtmlFile;
}

No comments:

Post a Comment