有关于.net 仿百度文库在线预览Word、Excel、PPT等office相关文件。这里我们使用Aspose相关组件,将office文件转化为Pdf格式文件存储或在线预览(Word可以存为Png格式,但是直接保存只会保存第一页)。
首先说转换为PDF格式存储和显示:
///
/// 将Word转换为Pdf
///
/// 文件地址
/// 保存地址
///
public bool Word2Pdf(string strFilePath,string savepath)
{
try
{
Aspose.Words.Document doc = new Aspose.Words.Document(strFilePath);
//将Word保存到指定路径下 savepath:保存路径
doc.Save(savepath, Aspose.Words.SaveFormat.Pdf);
//将Word保存至数据流中 再通过Response显示在页面中
MemoryStream memStream = new MemoryStream();
doc.Save(memStream, Aspose.Words.SaveFormat.Pdf);
byte[] bt = memStream.ToArray();
Response.ContentType = "application/pdf";
Response.OutputStream.Write(bt, 0, bt.Length);
return true;
}
catch (Exception)
{
return false;
}
}
然后,在线以图片的形式显示在网页上,分页显示调用一次显示一张图片,可以添加js做成类似于翻书的效果。
///
/// 将Word转换为Png
///
/// 文件地址
/// 要转换的页
///
public void Word2Png(string filepath, int pageIndex)
{
MemoryStream memStream = new MemoryStream();
Aspose.Words.Document doc = new Aspose.Words.Document(filepath);
PageInfo pageInfo = Document.GetPageInfo(pageIndex);
float scale = 100 / 100.0f;
const int Resolution = 96;
Size imgSize = pageInfo.GetSizeInPixels(scale, Resolution);
using (Bitmap img = new Bitmap(imgSize.Width, imgSize.Height))
{
img.SetResolution(Resolution, Resolution);
using (Graphics gfx = Graphics.FromImage(img))
{
gfx.Clear(Color.White);
Document.RenderToScale(pageIndex, gfx, 0, 0, scale);
img.Save(memStream, ImageFormat.Png);
}
}
}
// Send the bitmap data to the output stream.
Response.ContentType = "image/png";
byte[] imageData = memStream.ToArray();
Response.OutputStream.Write(imageData, 0, imageData.Length);
}
将Excel转换为Pdf格式显示或保存。
///
/// 将Word转换为Pdf
///
/// 文件地址
/// 保存地址
///
public bool Excel2Pdf(string fileName, string savepath)
{
try
{
Aspose.Cells.Workbook excel = new Aspose.Cells.Workbook(fileName);
//将ppt保存到指定路径下 savepath:保存路径
excel.Save(savepath, Aspose.Cells.SaveFormat.Pdf);
//将ppt保存至数据流中 再通过Response显示在页面中
MemoryStream memStream = new MemoryStream();
excel.Save(memStream, Aspose.Cells.SaveFormat.Pdf);
byte[] bt = memStream.ToArray();
Response.ContentType = "application/pdf";
Response.OutputStream.Write(bt, 0, bt.Length);
return true;
}
catch (Exception)
{
return false;
}
}
首先说转换为PDF格式存储和显示:
///
/// 转换ppt文件在线预览
///
/// 文件路径
/// 保存路径
///
public bool ppt2Pdf(string fileName, string savepath)
{
try
{
Aspose.Slides.Presentation ppt = new Aspose.Slides.Presentation(fileName);
//将ppt保存到指定路径下 savepath:保存路径
ppt.Save(savepath, Aspose.Slides.Export.SaveFormat.Pdf);
//将ppt保存至数据流中 再通过Response显示在页面中
MemoryStream memStream = new MemoryStream();
ppt.Save(memStream, Aspose.Slides.Export.SaveFormat.Pdf);
byte[] bt = memStream.ToArray();
Response.ContentType = "application/pdf";
Response.OutputStream.Write(bt, 0, bt.Length);
return true;
}
catch (Exception)
{
return false;
}
}
官网地址:www.aspose.com.
官方是要钱的,免费的大多数会有水印,不过神通广大的网友们还是有提供去除水印的dll,目前不知道是不是限时的。