admin管理员组文章数量:1593159
1、使用微软自带的dll文件进行转换,引用DLL文件,当前我这里显示的15.0.0,没有当前DLL的可以引用其他版本
2、实现代码
/// <summary>
/// OfficeDal转换相关操作
/// </summary>
public class OfficeDal
{
/// <summary>
/// Word文件转化为PDF
/// </summary>
/// <param name="SourcePath">Word文件路径</param>
/// <param name="SavePath">另存文件路径</param>
/// <param name="RandTime">随机字符串</param>
/// <param name="Extension">文件后缀名(例如:".pdf")</param>
/// <returns>返回转换成功的PDF文件路径</returns>
public static string WordToPDF(string SourcePath, string SavePath, string RandTime, string Extension)
{
if (string.IsNullOrEmpty(SourcePath))
{
return "";
}
先把文件的属性读取出来
//FileAttributes attrs = File.GetAttributes(SourcePath);
下面表达式中的 1 是 FileAttributes.ReadOnly 的值
此表达式是把 ReadOnly 所在的位改成 0,
//attrs = (FileAttributes)((int)attrs & ~(1));
修改为修改状态(非只读)
//File.SetAttributes(SourcePath, attrs);
Microsoft.Office.Interop.Word.Application application = new Microsoft.Office.Interop.Word.Application();
Microsoft.Office.Interop.Word.Document document = null;
object missing = System.Reflection.Missing.Value;
try
{
application.Visible = false;
//获取指定文件
document = application.Documents.Open(SourcePath);
string FileName = Path.GetFileNameWithoutExtension(SourcePath);
///文件新名称
string FileNameNew = "";
if (!String.IsNullOrEmpty(Extension))
{
FileNameNew = FileName + RandTime + Extension;
}
else
{
FileNameNew = FileName + RandTime + ".pdf";
}
///保存新的指定路径
string PDFPath = Path.Combine(SavePath, FileNameNew);
//判断路径是否存在
if (!Directory.Exists(SavePath))
{
Directory.CreateDirectory(SavePath);
}
if (document != null)
{
document.ExportAsFixedFormat(PDFPath, WdExportFormat.wdExportFormatPDF);
return PDFPath;
}
else
{
return "";
}
}
catch (Exception)
{
return "";
}
finally
{
if (document != null)
{
((_Document)document).Close(ref missing, ref missing, ref missing);
document = null;
}
if (application != null)
{
((_Application)application).Quit(ref missing, ref missing, ref missing);
application = null;
}
}
}
}
3、调用代码
///获取Word文件的绝对路径值
string FilePath = HttpContext.Current.Request.PhysicalApplicationPath + "ContractTemplateFile/ceshi.docx";
//保存文件相对路径
string FilePathNew = "/FilePDF/";
///防止文件保存一致性
string RandTime = DateTime.Now.ToString("yyyyMMddHHmmssffff");
///获取绝对路径,进行指定路径拼接。
string FilePathUpload = Server.MapPath("" + FilePathNew);
/*调用方法,返回保存位置*/
string ReturnPath = DHSite.OfficeDal.WordToPDF(FilePath, FilePathUpload, RandTime, ".pdf");
if (!String.IsNullOrEmpty(ReturnPath))
{
PathPDF = FilePathNew + Path.GetFileName(ReturnPath);
}
版权声明:本文标题:ASP.NET Word转换成PDF文件 内容由热心网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:https://m.elefans.com/dongtai/1728166150a1148042.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论