简体   繁体   中英

asp.net Microsoft.Office.Interop.Word

I am trying to get rid of empty pages that merge when the users views and prints the document. I am using the Dev express editor so the user inserts text that make the page over flow to other page (rtf) and creats an empty space. any way to stop this from happening>?

here my code:

     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();
    }
}
  }

Office interop is not supported from non user sessions (For example from a ASP.NET service), this may explain the strange behavior you are seeing.

You need to switch to a supported solution for manipulating documents from a non user session like the Open XML SDK before you attempt to correct any other problems.

UPDATE: re-reading your question, you are already using Open XML (the code in SearchAndReplace is already using it) you just need to replace the code in DoIt to use Open XML too.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM