Este artigo é um artigo espelhado de tradução automática, por favor clique aqui para ir para o artigo original.

Vista: 18870|Resposta: 1

[Fonte] .NET converte documentos do Word em arquivos PDF

[Copiar link]
Publicado em 16/12/2015 15: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. }
Copiar código
Citações necessáriasusando Microsoft.Office.Interop.Word;


Microsoft.Office.Interop.Word.rar (381.81 KB, Número de downloads: 0)




Anterior:O net utiliza a porta de escuta HttpListener
Próximo:O WPF altera os itens padrão para a janela de lançamento
Publicado em 17/12/2015 01:52:00 |
{:1_1:
Disclaimer:
Todo software, material de programação ou artigos publicados pela Code Farmer Network são apenas para fins de aprendizado e pesquisa; O conteúdo acima não deve ser usado para fins comerciais ou ilegais, caso contrário, os usuários terão todas as consequências. As informações deste site vêm da Internet, e disputas de direitos autorais não têm nada a ver com este site. Você deve deletar completamente o conteúdo acima do seu computador em até 24 horas após o download. Se você gosta do programa, por favor, apoie um software genuíno, compre o registro e obtenha serviços genuínos melhores. Se houver qualquer infração, por favor, entre em contato conosco por e-mail.

Mail To:help@itsvse.com