Ms word 将多个文档与Word.Application(COM互操作)组合会导致格式错误吗?

Ms word 将多个文档与Word.Application(COM互操作)组合会导致格式错误吗?,ms-word,office-interop,Ms Word,Office Interop,使用.net 4.0/vs2010、office 2007 请注意,我对实现最终结果的任何其他方法都持开放态度。我没有嫁给Word,但我有不能包括任何许可的第三方工具(无Aspose)的限制,我想尽量减少用户机器上的任何安装。这是一个公司环境,所以我有一些控制权 我需要打印2或3字的文件作为一个单一的文件。我的代码如下所示,它可以工作。。。。除了第二个文档的格式总是有点偏离(段落间距、字体、边距)。奇怪的是,第三个文档(它有不同的页面方向)很好。有时用户需要将文档发送到传真服务器,因此第一页将是

使用.net 4.0/vs2010、office 2007

请注意,我对实现最终结果的任何其他方法都持开放态度。我没有嫁给Word,但我有不能包括任何许可的第三方工具(无Aspose)的限制,我想尽量减少用户机器上的任何安装。这是一个公司环境,所以我有一些控制权

我需要打印2或3字的文件作为一个单一的文件。我的代码如下所示,它可以工作。。。。除了第二个文档的格式总是有点偏离(段落间距、字体、边距)。奇怪的是,第三个文档(它有不同的页面方向)很好。有时用户需要将文档发送到传真服务器,因此第一页将是传真封面

我在哪里失败??方法KillCom(对象o)调用System.Runtime.InteropServices.Marshal.ReleaseComObject(o)

public void CombineMultipleDocuments(字符串coverSheetPath、字符串[]documentpath、字符串destinationFile、bool makeVisible)
{
列表单据=新建列表();
if(string.IsNullOrWhiteSpace(destinationFile))
抛出新ArgumentException(“需要destinationfile”);
尝试
{
//剥离无效路径
foreach(documentpath中的字符串p)
{
如果(!string.IsNullOrWhiteSpace(p)和&File.Exists(p))
{
新增(p);
}
}
如果(docs.Count==0)
抛出新的ArgumentException(“没有要打印的文档”);
//打开封面
wrdApp=新单词.Application();
wrdApp.Visible=makeVisible;
//如果没有封面页,请打开第一份文档并将剩余文档附加到其中
if(string.IsNullOrWhiteSpace(coverSheetPath))
{
coverSheetPath=docs[0];
文件移除(0);
}
wrdDoc=wrdApp.Documents.Open(封面页路径、参考信息、参考信息、参考信息、参考信息、参考信息
,引用省略,引用省略,引用省略,引用省略,引用省略,引用省略,引用省略,引用省略,引用省略,引用省略,引用省略
,引用引用,引用引用引用);
wrdRange=wrdDoc.Content;
//一点空间
wrdRange.InsertParagraphAfter();
//附上其余的文件
foreach(文档中的字符串路径)
{
//打开要插入的新源文档
Word.\u Document newDoc=wrdApp.Documents.Open(路径、引用、引用、引用、引用
,引用省略,引用省略,引用省略,引用省略,引用省略,引用省略,引用省略,引用省略,引用省略,引用省略,引用省略
,引用引用,引用引用引用);
//继续分页符
wrdRange.collapseDirection(Word.WdCollapseDirection.wdCollapseEnd);
wrdRange.InsertBreak(Microsoft.Office.Interop.Word.WdBreakType.wdSectionBreakNextPage);
//为我们的新内容创建一个新部分
Word.Section sec=wrdRange.Sections.Add(参考信息,参考信息);
//复制源文档的样式、字体等
sec.PageSetup.Orientation=newDoc.PageSetup.Orientation;
sec.Range.Font=newDoc.Content.Font;
//取消页脚和页眉的链接
页脚[Word.WdHeaderFooterIndex.wdheaderfooterprismary].LinkToPrevious=false;
sec.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.FormattedText=newDoc.Sections[1]。Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.FormattedText;
sec.Header[Word.WdHeaderFooterIndex.WDHeaderFooterPreprimary].LinkToPrevious=false;
sec.Header[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.FormattedText=newDoc.Sections[1]。Header[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.FormattedText;
wrdRange.FormattedText=newDoc.Content.FormattedText;
//接近
newDoc.Saved=true;
newDoc.Close(引用ALSE,引用OMISING,引用OMISING);
newDoc=null;
KillCOM(newDoc);
}
//日记功能需要设置这些变量
Word.Variables wrdVars=wrdDoc.Variables;
wrdVars.添加(“字母”,WrdPropLETTER_NAME);
添加(“FileKey”,WrdPropFILE_KEY);
添加(“字母到”,字母到);
wrdVars.Add(“LetterFirstName”,WrdPropLETTER_FNAME);
wrdVars.Add(“LetterLastName”,WrdPropLETTER_LNAME);
添加(“LetterCompany”,WrdPropLETTER_COMPANY);
添加(“字母类别”,字母类别);
wrdVars.Add(“CurrentHeaderDoc”,WrdPropCUR_HEADERDOC);
添加(“当前数据文档”,WrdPropCUR\u数据文档);
wrdDoc.Protect(Word.WdProtectionType.wdAllowOnlyFormFields,引用“mojojojo”);
wrdDoc.SaveAs(目标文件,引用引用引用,引用引用引用,引用引用引用,引用引用引用,引用引用引用
,引用省略,引用省略,引用省略,引用省略,引用省略,引用省略,引用省略,引用省略,引用省略,引用省略,引用省略
,引用引用,引用引用引用);
//隐藏时关闭
如果(!makeVisible)
{
wrdDoc.Saved=true;
wrdDoc.Close(参考ALSE,参考OMISING,参考OMISING);
 public void CombineMultipleDocuments(string coverSheetPath, string[] documentPaths, string destinationFile, bool makeVisible)
        {
            List<string> docs = new List<string>();

            if (string.IsNullOrWhiteSpace(destinationFile))
                throw new ArgumentException("The destinationfile is required");
            try
            {
                //strip invalid paths
                foreach (string p in documentPaths)
                {
                    if (!string.IsNullOrWhiteSpace(p) && File.Exists(p))
                    {
                        docs.Add(p);
                    }
                }

                if (docs.Count == 0)
                    throw new ArgumentException("There are no documents to print");
                //open the cover sheet
                wrdApp = new Word.Application();
                wrdApp.Visible = makeVisible;

                //if there is no cover sheet open the first document and append the remaining docs to it
                if (string.IsNullOrWhiteSpace(coverSheetPath))
                {
                    coverSheetPath = docs[0];
                    docs.RemoveAt(0);
                }
                wrdDoc = wrdApp.Documents.Open(coverSheetPath, 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);
                wrdRange = wrdDoc.Content;

                //a little space
                wrdRange.InsertParagraphAfter();
                //attach the rest of the documents
                foreach (string path in docs)
                {
                    //open the new source document to be inserted
                    Word._Document newDoc = wrdApp.Documents.Open(path, 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);

                    //continues page break
                    wrdRange.Collapse(Word.WdCollapseDirection.wdCollapseEnd);
                    wrdRange.InsertBreak(Microsoft.Office.Interop.Word.WdBreakType.wdSectionBreakNextPage);

                    //create a new section for our new content
                    Word.Section sec = wrdRange.Sections.Add(ref oMissing, ref oMissing);

                    //copy the source document's styles, fonts, etc
                    sec.PageSetup.Orientation = newDoc.PageSetup.Orientation;

                    sec.Range.Font = newDoc.Content.Font;

                    //unlink footer and headers
                    sec.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].LinkToPrevious = false;
                    sec.Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.FormattedText = newDoc.Sections[1].Footers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.FormattedText;

                    sec.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].LinkToPrevious = false;
                    sec.Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.FormattedText = newDoc.Sections[1].Headers[Word.WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.FormattedText;

                    wrdRange.FormattedText = newDoc.Content.FormattedText;


                    //close
                    newDoc.Saved = true;
                    newDoc.Close(ref oFalse, ref oMissing, ref oMissing);
                    newDoc = null;
                    KillCOM(newDoc);

                }

                //the diary function needs these variables to be set
                Word.Variables wrdVars = wrdDoc.Variables;

                wrdVars.Add("Letter", WrdPropLETTER_NAME);
                wrdVars.Add("FileKey", WrdPropFILE_KEY);
                wrdVars.Add("LetterTo", WrdPropLETTER_TO);
                wrdVars.Add("LetterFirstName", WrdPropLETTER_FNAME);
                wrdVars.Add("LetterLastName", WrdPropLETTER_LNAME);
                wrdVars.Add("LetterCompany", WrdPropLETTER_COMPANY);
                wrdVars.Add("LetterCategory", WrdPropLETTER_CATEGORY);
                wrdVars.Add("CurrentHeaderDoc",WrdPropCUR_HEADERDOC);
                wrdVars.Add("CurrentDataDoc", WrdPropCUR_DATADOC);


                wrdDoc.Protect(Word.WdProtectionType.wdAllowOnlyFormFields, ref oMissing, "mojojojo");
                wrdDoc.SaveAs(destinationFile, 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);

                //close if hidden
                if (!makeVisible)
                {
                    wrdDoc.Saved = true;
                    wrdDoc.Close(ref oFalse, ref oMissing, ref oMissing);

                    wrdApp.Quit(ref oFalse, ref oMissing, ref oMissing);
                    wrdDoc = null;
                    wrdApp = null;
                }

                //clean up
                if (File.Exists(coverSheetPath))
                    File.Delete(coverSheetPath);
                foreach (string path in documentPaths)
                {
                    if (File.Exists(path))
                        File.Delete(path);
                }
            }
            catch (Exception e)
            {
                string error = e.ToString();
            }
            finally
            {
                wrdRange = null;
                wrdDoc = null;
                wrdApp = null;
                KillCOM(wrdRange);
                KillCOM(wrdDoc);
                KillCOM(wrdApp);

            }

        }
 void mergeDocumentsTest(List<string> documentFiles)
 {

        _Application oWord = new Microsoft.Office.Interop.Word.Application();
        _Document oDoc = oWord.Documents.Add();
        Selection oSelection = oWord.Selection;

        foreach (string documentFile in documentFiles)
        {
            _Document oCurrentDocument = oWord.Documents.Add(documentFile);
            copyPageSetup(oCurrentDocument.PageSetup, oDoc.Sections.Last.PageSetup);
            oCurrentDocument.Range().Copy();
            oSelection.PasteAndFormat(WdRecoveryType.wdFormatOriginalFormatting);
            if (!Object.ReferenceEquals(documentFile, documentFiles.Last()))
                oSelection.InsertBreak(WdBreakType.wdSectionBreakNextPage);
        }

        oDoc.SaveAs("testdoc.doc");
        oDoc.Close();

        //TODO: release objects, close word application

    }

    void copyPageSetup(PageSetup source, PageSetup target)
    {
        target.PaperSize = source.PaperSize;

        //target.Orientation = source.Orientation; //not working in word 2003, so here is another way
        if (!source.Orientation.Equals(target.Orientation))
            target.TogglePortrait();

        target.TopMargin = source.TopMargin;
        target.BottomMargin = source.BottomMargin;
        target.RightMargin = source.RightMargin;
        target.LeftMargin = source.LeftMargin;
        target.FooterDistance = source.FooterDistance;
        target.HeaderDistance = source.HeaderDistance;
        target.LayoutMode = source.LayoutMode;
    }