이 글은 기계 번역의 미러 문서이며, 원본 기사로 바로 이동하려면 여기를 클릭해 주세요.

보기: 18870|회답: 1

[출처] .NET은 워드 문서를 PDF 파일로 변환합니다

[링크 복사]
게시됨 2015. 12. 16. 오후 3:49:24 | | |
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Web;
  5. using System.Web.Mvc;
  6. using Microsoft.Office.Interop.Word;

  7. namespace MvcApplication1.Controllers
  8. {
  9.     public class HomeController : Controller
  10.     {
  11.         //
  12.         // GET: /Home/
  13.         public ActionResult Index(string type, int id = 0)
  14.         {
  15.             ViewBag.ID = id;
  16.             ViewBag.Type = type;
  17.             return View();
  18.         }

  19.         [HttpPost]
  20.         public ActionResult Index(FormCollection collection)
  21.         {
  22.             Toprint();

  23.             return View();
  24.         }

  25.         public void Toprint()
  26.         {
  27.             WriteIntoWord wiw = new WriteIntoWord();
  28.             string FilePath = Server.MapPath("jkxy01.dot"); //模板路径

  29.             var filename = "qjjf" + DateTime.Now.ToString("yyyyMMddHHmmss");
  30.             string Bookmarkjkqx = "jkqx";
  31.             string Filljkqx = "400";

  32.             string SaveDocPath = Server.MapPath(filename+".doc");
  33.             wiw.OpenDocument(FilePath);

  34.             //写入书签
  35.             wiw.WriteIntoDocument("IdCard", "123");
  36.             wiw.WriteIntoDocument("chujieren", "借款人");
  37.             wiw.WriteIntoDocument(Bookmarkjkqx, Filljkqx);

  38.             wiw.Save_CloseDocument(SaveDocPath);

  39.             //转成pdf
  40.            string SavePdfPath = Server.MapPath("contract/"+filename+".pdf");
  41.            var flag= wiw.WordToPdf(SaveDocPath, SavePdfPath);
  42.             if (flag)
  43.             {
  44.                 //删除临时word,
  45.                 System.IO.File.Delete(SaveDocPath);
  46.             }
  47.         }
  48.     }

  49.     public class WriteIntoWord
  50.     {
  51.         private ApplicationClass app = null; //定义应用程序对象
  52.         private Document doc = null; //定义 word 文档对象
  53.         private Object missing = System.Reflection.Missing.Value; //定义空变量
  54.         private Object isReadOnly = false;
  55.         // 向 word 文档写入数据
  56.         public void OpenDocument(string FilePath)
  57.         {
  58.             object filePath = FilePath; //文档路径
  59.             app = new ApplicationClass(); //打开文档
  60.             doc = app.Documents.Open(ref filePath, ref missing, ref missing, ref missing,
  61.                                      ref missing, ref missing, ref missing, ref missing);
  62.             doc.Activate(); //激活文档
  63.         }

  64.         /// <summary>
  65.         ///   打开word,将对应数据写入word里对应书签域
  66.         /// </summary>
  67.         ///<param name="parLableName">域标签</param>
  68.         /// <param name="parFillName">写入域中的内容</param>  
  69.      
  70.         public void WriteIntoDocument(string BookmarkName, string FillName)
  71.         {
  72.             object bookmarkName = BookmarkName;
  73.             Bookmark bm = doc.Bookmarks.get_Item(ref bookmarkName); //返回书签
  74.             bm.Range.Text = FillName; //设置书签域的内容
  75.         }

  76.         /// <summary>
  77.         /// 保存并关闭
  78.         /// </summary>
  79.         /// <param name="parSaveDocPath">文档另存为的路径</param>
  80.         ///
  81.         public void Save_CloseDocument(string SaveDocPath)
  82.         {
  83.             object savePath = SaveDocPath; //文档另存为的路径
  84.             Object saveChanges = app.Options.BackgroundSave; //文档另存为
  85.             doc.SaveAs(ref savePath, ref missing, ref missing, ref missing, ref missing,
  86.                        ref missing, ref missing, ref missing);
  87.             doc.Close(ref saveChanges, ref missing, ref missing); //关闭文档
  88.             app.Quit(ref missing, ref missing, ref missing); //关闭应用程序

  89.         }

  90.         /// <summary>

  91.         /// 把Word文件转换成pdf文件

  92.         /// </summary>

  93.         /// <param name="sourcePath">需要转换的文件路径和文件名称</param>

  94.         /// <param name="targetPath">转换完成后的文件的路径和文件名名称</param>

  95.         /// <returns>成功返回true,失败返回false</returns>

  96.         public  bool WordToPdf(object sourcePath, string targetPath)
  97.         {

  98.             bool result = false;

  99.             WdExportFormat wdExportFormatPDF = WdExportFormat.wdExportFormatPDF;

  100.             object missing = Type.Missing;

  101.             Microsoft.Office.Interop.Word.ApplicationClass applicationClass = null;

  102.             Document document = null;

  103.             try
  104.             {

  105.                 applicationClass = new Microsoft.Office.Interop.Word.ApplicationClass();

  106.                 document = applicationClass.Documents.Open(ref sourcePath, 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, ref missing);

  107.                 if (document != null)
  108.                 {

  109.                     document.ExportAsFixedFormat(targetPath, wdExportFormatPDF, false, WdExportOptimizeFor.wdExportOptimizeForPrint, WdExportRange.wdExportAllDocument, 0, 0, WdExportItem.wdExportDocumentContent, true, true, WdExportCreateBookmarks.wdExportCreateWordBookmarks, true, true, false, ref missing);

  110.                 }

  111.                 result = true;

  112.             }

  113.             catch
  114.             {

  115.                 result = false;

  116.             }

  117.             finally
  118.             {

  119.                 if (document != null)
  120.                 {

  121.                     document.Close(ref missing, ref missing, ref missing);

  122.                     document = null;

  123.                 }

  124.                 if (applicationClass != null)
  125.                 {

  126.                     applicationClass.Quit(ref missing, ref missing, ref missing);

  127.                     applicationClass = null;

  128.                 }

  129.             }

  130.             return result;

  131.         }
  132.     }
  133. }
코드 복사
출처 필요Microsoft.Office.Interop.Word 사용;


Microsoft.Office.Interop.Word.rar (381.81 KB, 다운로드 횟수: 0)




이전의:net은 HttpListener 리스닝 포트를 사용합니다
다음:WPF는 런치 창의 기본 항목을 변경합니다
게시됨 2015. 12. 17. 오전 1:52:00 |
{:1_1:
면책 조항:
Code Farmer Network에서 발행하는 모든 소프트웨어, 프로그래밍 자료 또는 기사는 학습 및 연구 목적으로만 사용됩니다; 위 내용은 상업적 또는 불법적인 목적으로 사용되지 않으며, 그렇지 않으면 모든 책임이 사용자에게 부담됩니다. 이 사이트의 정보는 인터넷에서 가져온 것이며, 저작권 분쟁은 이 사이트와는 관련이 없습니다. 위 내용은 다운로드 후 24시간 이내에 컴퓨터에서 완전히 삭제해야 합니다. 프로그램이 마음에 드신다면, 진짜 소프트웨어를 지원하고, 등록을 구매하며, 더 나은 진짜 서비스를 받아주세요. 침해가 있을 경우 이메일로 연락해 주시기 바랍니다.

Mail To:help@itsvse.com