2025年4月15日 星期二 乙巳(蛇)年 正月十六 设为首页 加入收藏
rss
您当前的位置:首页 > 计算机 > 编程开发 > .net

c#word转换pdf

时间:11-08来源:作者:点击数:26

首先呢,在项目中创建一个文件夹 wordpath,这个文件夹是存放你的word和pdf的。

首先要准备一个word放进去(.doc)。

这个呢也是需要引用的,这个引用2015中就有 引用-添加引用-扩展 Microsoft.Office.Interop.Word.dll

然后呢 准备copy代码

  • public bool WordToPDF(string sourcePath)
  • {
  • bool result = false;
  • Word.Application application = new Word.Application();
  • Word.Document document = null;
  • try
  • {
  • application.Visible = false;
  • document = application.Documents.Open(sourcePath);
  • string PDFPath = sourcePath.Replace(".doc", ".pdf");//pdf存放位置
  • if (!File.Exists(@PDFPath))//存在PDF,不需要继续转换
  • {
  • document.ExportAsFixedFormat(PDFPath, Word.WdExportFormat.wdExportFormatPDF);
  • }
  • result = true;
  • }
  • catch (Exception e)
  • {
  • Console.WriteLine(e.Message);
  • result = false;
  • }
  • finally
  • {
  • document.Close();
  • }
  • return result;
  • }

贴上去之后你会发现 你的引用没加 会报错呦,因此就要加一个引用,像这样using Word = Microsoft.Office.Interop.Word;

等你加完引用之后 你会发现 艾玛 应该没什么问题了,有问题的话 你可以百度查查。哈哈哈...

其次就是找个地方调用了,这里呢就在Page_Load里面调用了

  •        if (!IsPostBack)
  • {
  • string strWord = Server.MapPath("/wordpath/***.doc");//文档路径
  • WordToPDF(strWord);
  • string browsertype = Page.Request.Browser.Type;//浏览器类型判断
  • if (browsertype != "IE6" && browsertype != "IE7")
  • {
  •         //这里是生成好的pdf是做一个显示,在这一步之前 pdf已经生成好了
  • Response.Write("<script language='javascript'>window.open('/wordpath/***.pdf');</script>");
  • }
  • }

就是用微软的一个方法 以 PDF 或 XPS 格式保存文档。

如果需要扩展可以去官网看看

https://docs.microsoft.com/zh-cn/previous-versions/visualstudio/visual-studio-2010/bb398522(v=vs.100)

方便获取更多学习、工作、生活信息请关注本站微信公众号城东书院 微信服务号城东书院 微信订阅号
推荐内容
相关内容
栏目更新
栏目热门