您的位置:首页 > 编程语言 > ASP

Asp.Net(C#) Word(doc)转换为PDF

2011-03-02 22:20 471 查看
近在做一个东西:

任务描述:用户上传Word文件到服务器,系统将Word文件转换为PDF格式,其他用户以PDF格式浏览该文件。

实现思路:

方案一:找一个在线编辑器(类FCKeiditor),直接让用户在编辑器中编辑需上传内容,将其内容以网页的形式呈现。

实施结果:失败

原因:类FCK编辑器,功能很强大,但是不适合长篇幅数据编辑,尤其是附图内容。一方面用户操作不方便(用户更习惯word),另一方面内容呈现方面不尽如人意。最终放弃。

方案二:将word上传装换为Html,以html静态页呈现。

方案评价:实现简单,对纯文本内容,表格效果还不错,但如果word中有图片,会出现变形。(效果同将word直接另存为html格式)

部分代码:ASPX页面需要一个FileUpload和一个Button

protected Microsoft.Office.Interop.Word.ApplicationClass objWord = new ApplicationClass();
protected string strPathToUpload; //Path to upload files "Uploaded"
protected string strPathToConvert; //Path to convert uploaded files and save
object fltDocFormat = 10; //For filtered HTML Output
protected object missing = System.Reflection.Missing.Value;
protected object readOnly = false; //Open file in readOnly mode
protected object isVisible = false;//The process has to be in invisible mode

protected void btnUpload_Click(object sender, EventArgs e)
{
if (!(fUpload.HasFile))
{
lblMessage.Text = "选择要上传的文件";
}
else
{
try
{
//To check the file extension if it is word document or something else
string strFileName = fUpload.FileName;
string[] strSep = fUpload.FileName.Split('.');
int arrLength = strSep.Length - 1;
string strExt = strSep[arrLength].ToString().ToUpper();
//Save the uploaded file to the folder
strPathToUpload = Server.MapPath("Uploaded");
//Map-path to the folder where html to be saved
strPathToConvert = Server.MapPath("WordToHtml");
object FileName = strPathToUpload + "//" + fUpload.FileName;
object FileToSave = strPathToConvert + "//" + fUpload.FileName + ".htm";
if (strExt.ToUpper().Equals("DOC"))
{
fUpload.SaveAs(strPathToUpload + "//" + fUpload.FileName);
lblMessage.Text = "File uploaded successfully";
//open the file internally in word. In the method all the parameters should be passed by object reference
objWord.Documents.Open(ref FileName, ref readOnly, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref isVisible, ref missing, ref missing, ref missing, ref missing, ref missing);
//Do the background activity
objWord.Visible = false;
Microsoft.Office.Interop.Word.Document oDoc = objWord.ActiveDocument;
oDoc.SaveAs(ref FileToSave, ref fltDocFormat, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing, ref missing);
lblMessage.Text = fUpload.FileName +" converted to HTML successfully";
}
else
{
lblMessage.Text = "Invalid file selected!";
}
//Close/quit word
objWord.Quit(ref missing, ref missing, ref missing);
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
}
}


方案三:将word转换为PDF格式,网上很多文章说用itextsharp,看了itextsharp的一些例子,更多的是将一些内容组织到PDF中,代码量很大,内容控制很繁琐。没发现ITextsharp能直接将Word转换为PDF。有高人实现该功能,望不吝赐教。

方案四:参考http://www.cnblogs.com/ghd258/articles/258060.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: