2015-07-22 5 views
-1

Я пытаюсь избавиться от пустых страниц, которые сливаются, когда пользователи просматривают и печатают документ. Я использую редактор Dev express, поэтому пользователь вставляет текст, который переводит страницу на другую страницу (rtf), и создает пустое пространство. любой способ остановить это?>asp.net Microsoft.Office.Interop.Word

вот мой код:

 using System; 
    using System.Collections.Generic; 
    using System.Drawing.Imaging; 
    using System.Linq; 
    using System.IO; 
    using System.Text; 
    using System.Text.RegularExpressions; 
    using System.Threading.Tasks; 
    using System.Xml; 
    using System.Xml.Linq; 
    using DocumentFormat.OpenXml.Packaging; 


    using Microsoft.Office.Interop.Word; 
    using WordApplication = Microsoft.Office.Interop.Word.Application; 


    namespace DocumentMapper 
    { 
    public class XmlDocumentMapper 
    { 
    /// <summary> 
    /// Use to replace all text elements included in template text. 
    /// </summary> 
    /// <param name="mergeDocInfo"></param> 
    /// <param name="html"></param> 
    /// <returns></returns> 
    public static string MergeHtml(MergeDocInfo mergeDocInfo, string html) 
    { 
     return MergeText(mergeDocInfo.MergeValues, html); 
    } 

    public static string MergeHtml(Dictionary<string, string> mergeValues, string html) 
    { 
     return MergeText(mergeValues, html); 
    } 

    public static string MergeHtml(MergeDocInfo mergeDocInfo) 
    { 
     string htmlText = null; 
     string template = string.Format("{0}{1}", mergeDocInfo.TemplatePath, mergeDocInfo.TemplateName.Replace(".docx", ".html")); 
     using (Stream stream = new FileStream(template, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) 
     { 
      using (StreamReader sr = new StreamReader(stream)) 
      { 
       htmlText = sr.ReadToEnd(); 
      } 
     } 

     return MergeText(mergeDocInfo.MergeValues, htmlText); 
    } 

    public static void SearchAndReplace(MergeDocInfo mergeDocInfo) 
    { 
     string template = string.Format("{0}{1}", mergeDocInfo.TemplatePath, mergeDocInfo.TemplateName); 
     string document = string.Format("{0}{1}", mergeDocInfo.MergeDocPath, mergeDocInfo.MergeDocName); 
     using (Stream stream = new FileStream(template, FileMode.Open, FileAccess.Read, FileShare.ReadWrite)) 
     using (WordprocessingDocument wordTemplate = WordprocessingDocument.Open(stream, false)) 
     using (WordprocessingDocument wordDocument = WordprocessingDocument.Create(document, DocumentFormat.OpenXml.WordprocessingDocumentType.Document)) 
     { 
      foreach (var part in wordTemplate.Parts) 
       wordDocument.AddPart(part.OpenXmlPart, part.RelationshipId); 

      string docText = null; 
      using (StreamReader sr = new StreamReader(wordTemplate.MainDocumentPart.GetStream())) 
      { 
       docText = sr.ReadToEnd(); 
      } 

      docText = MergeText(mergeDocInfo.MergeValues, docText); 

      using (StreamWriter sw = new StreamWriter(wordDocument.MainDocumentPart.GetStream(FileMode.Create))) 
      { 
       sw.Write(docText); 
      } 
     } 

     FileInfo tempFile = new FileInfo(document); 
     FileInfo mergeFile = new FileInfo(document.Replace(".docx", ".pdf")); 

     DoIt(tempFile, mergeFile); 
    } 

    private static string MergeText(Dictionary<string, string> mergeValues, string text) 
    { 
     var dateValues = new Dictionary<string, string>(); 
     foreach (KeyValuePair<string, string> pair in mergeValues) 
     { 
      DateTime dt; 
      if (DateTime.TryParse(pair.Value, out dt)) 
      { 
       dateValues.Add(pair.Key, pair.Value); 
      } 
     } 

     foreach (KeyValuePair<string, string> pair in dateValues) 
     { 
      mergeValues[pair.Key] = DateTime.Parse(pair.Value).ToShortDateString(); 
     } 

     foreach (KeyValuePair<string, string> pair in mergeValues) 
     { 
      if (!string.IsNullOrEmpty(pair.Key)) 
      { 
       text = new Regex(pair.Key).Replace(text, string.IsNullOrEmpty(pair.Value) ? "_____" : pair.Value); 
      } 
     } 

     return text; 
    } 

    /// <summary> 
    /// Obsolete 
    /// </summary> 
    /// <param name="tempFile"></param> 
    /// <param name="mergeFile"></param> 
    private static void DoIt(FileInfo tempFile, FileInfo mergeFile) 
    { 
     WordApplication word = new WordApplication() 
     { 
      Visible = false, 
      ScreenUpdating = false 
     }; 

     object oMissing = System.Reflection.Missing.Value; 
     Object filename = (Object)tempFile.FullName; 

     Document doc = word.Documents.Open(ref filename, ref oMissing, 
      ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, 
      ref oMissing, ref oMissing, ref oMissing, ref oMissing, ref oMissing, 
      ref oMissing, ref oMissing, ref oMissing, ref oMissing); 
     doc.Activate(); 

     object outputFileName = (Object)mergeFile.FullName; 
     object fileFormat = WdSaveFormat.wdFormatPDF; 

     doc.SaveAs(ref outputFileName, 
      ref fileFormat, ref oMissing, ref oMissing, 
      ref oMissing, ref oMissing, ref oMissing, ref oMissing, 
      ref oMissing, ref oMissing, ref oMissing, ref oMissing, 
      ref oMissing, ref oMissing, ref oMissing, ref oMissing); 

     object saveChanges = WdSaveOptions.wdDoNotSaveChanges; 
     ((_Document)doc).Close(ref saveChanges, ref oMissing, ref oMissing); 
     doc = null; 

     ((_Application)word).Quit(ref oMissing, ref oMissing, ref oMissing); 
     word = null; 

     tempFile.Delete(); 
    } 
} 
    } 
+1

Корпорация Майкрософт настоятельно рекомендует использовать автоматизацию Office (и, следовательно, Word Interop) на сервере. Прежде чем перейти к чему-либо еще, я бы предложил рефакторинг для удаления кода автоматизации из любых связанных с сервером процессов, возможно, путем получения пользовательских запросов и запуска автоматизации в автономном режиме, которые будут отправлены пользователю позже. https://support.microsoft.com/en-us/kb/257757 – maniak1982

+0

При написании вопроса о переполнении стека задайте свой вопрос заголовком, который соответствующим образом описывает проблему (не просто бросайте теги в заголовок) и потратьте некоторое время, убедившись, что ваш вопрос имеет правильную грамматику. – mason

ответ

1

Office interop is not supported from non user sessions (например, из службы ASP.NET), это может объяснить странное поведение, которое вы видите.

Перед попыткой исправить любые другие проблемы вам необходимо перейти на поддерживаемое решение для управления документами из не-пользовательского сеанса, например Open XML SDK.

UPDATE: перечитывая свой вопрос, вы уже используете Open XML (код в SearchAndReplace уже использует его) нужно просто заменить код в DoIt использовать Open XML тоже.

+0

переключается с офиса interop, чтобы открыть xml sdk длинный процесс? –

+0

Вам потребуется переписать часть вашего кода, но это не слишком сложно. См. [Этот старый мой ответ] (http://stackoverflow.com/questions/5490493/using-sharepoint-word-automation-to-do-a-text-replace/5491122#5491122) для примера того, какое слово заменить код выглядит как (Ответ на sharepoint вместо ASP.NET, но вы можете получить основную суть этого, просто посмотрите на часть внутри блока 'using (WordprocessingDocument ...', то есть часть Open XML) –

+0

HOLD UP !!, перечитывая свой вопрос, вы уже используете Open XML (см. 'Using DocumentFormat.OpenXml.Packaging;'), вам просто нужно заменить код в 'DoIt', чтобы использовать Open XML вместо офисного взаимодействия , –

Смежные вопросы