Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/302.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 合并docx文件,包括页眉、页脚和图片_C#_Winforms_Pdf_Docx - Fatal编程技术网

C# 合并docx文件,包括页眉、页脚和图片

C# 合并docx文件,包括页眉、页脚和图片,c#,winforms,pdf,docx,C#,Winforms,Pdf,Docx,我必须将多个DOCX文件(用创建)合并到一个大文件中。我已经设法合并了多个文件,但我无法合并页眉和页脚(它们在文件和页面之间有所不同)。我尝试了和MS Office COM互操作,但它根本不想合并页眉/页脚。它们被跳过了 有人能提供有效的解决方案吗?可以是任何东西(包括使用PDFCreator COM转换为PDF,或互操作或其他) 我还尝试了C#中的PDFCreator示例,它很好地将一个文档转换为PDF,但我不知道如何为它提供多个文档,这样它就可以创建一个大的PDF。因此,如果有人能提供一个好

我必须将多个DOCX文件(用创建)合并到一个大文件中。我已经设法合并了多个文件,但我无法合并页眉和页脚(它们在文件和页面之间有所不同)。我尝试了和MS Office COM互操作,但它根本不想合并页眉/页脚。它们被跳过了

有人能提供有效的解决方案吗?可以是任何东西(包括使用PDFCreator COM转换为PDF,或互操作或其他)

我还尝试了C#中的PDFCreator示例,它很好地将一个文档转换为PDF,但我不知道如何为它提供多个文档,这样它就可以创建一个大的PDF。因此,如果有人能提供一个好的(免费)方式,我们将不胜感激

这就是我使用的:

internal static class DocumentsMerging {
    private static object missing = Type.Missing;
    private static ApplicationClass wordApplication { get; set; }
    private static void addDocument(object path, Document doc, bool firstDocument) {
        object subDocPath = path;
        var subDoc = wordApplication.Documents.Open(ref subDocPath, 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);
        try {
            if (!firstDocument) {
                insertPageBreak(doc);
            }
            object docStart = doc.Content.End - 1;
            object docEnd = doc.Content.End;
            object start = subDoc.Content.Start;
            object end = subDoc.Content.End;
            Range rng = doc.Range(ref docStart, ref docEnd);
            rng.FormattedText = subDoc.Range(ref start, ref end);
            //if (!lastDocument) {
            //}
        } finally {
            subDoc.Close(ref missing, ref missing, ref missing);
        }
    }
    public static bool deleteFile(string fileName) {
        if (File.Exists(fileName)) {
            try {
                File.Delete(fileName);
                if (File.Exists(fileName)) {
                    return false;
                }
                return true;
            } catch (IOException) {
                DialogResult result = MessageBox.Show(new Form {TopMost = true}, "Plik " + fileName + " jest w użyciu lub nie masz uprawnień do zapisania raportu w tym miejscu. Czy chcesz spróbować ponownie?", "Błąd zapisu (000002)", MessageBoxButtons.YesNo, MessageBoxIcon.Stop);
                if (result == DialogResult.No) {
                    return false;
                }
                if (deleteFile(fileName)) {
                    return true;
                }
            } catch (Exception e) {
                MessageBox.Show(new Form {TopMost = true}, "Plik " + fileName + " nie może zostać skasowany. Błąd " + Environment.NewLine + Environment.NewLine + e, "Błąd zapisu (000003)", MessageBoxButtons.YesNo, MessageBoxIcon.Stop);
                return false;
            }
        } else {
            return true;
        }
        return false;
    }
    public static void documentsMerge(object fileName, List<string> arrayList) {
        // object fileName = Path.Combine(Environment.CurrentDirectory, @"NewDocument.doc");
        bool varTest = deleteFile(fileName.ToString());
        if (varTest) {
            try {
                wordApplication = new ApplicationClass();
                var doc = wordApplication.Documents.Add(ref missing, ref missing, ref missing, ref missing);
                try {
                    doc.Activate();
                    int count = 0;
                    foreach (var alItem in arrayList) {
                        addDocument(alItem, doc, count == 0);
                        count++;
                    }
                    // addDocument(@"D:\Projects\WordTests\ConsoleApplication1\Documents\Doc1.doc", doc ) ; //, false);
                    // addDocument(@"D:\Projects\WordTests\ConsoleApplication1\Documents\Doc2.doc", doc ) ; //, true);
                    doc.SaveAs(ref fileName, 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);
                } finally {
                    doc.Close(ref missing, ref missing, ref missing);
                }
            } finally {
                wordApplication.Quit(ref missing, ref missing, ref missing);
            }
        } else {
            return;
        }
    }
    private static void insertPageBreak(Document doc) {
        object docStart = doc.Content.End - 1;
        object docEnd = doc.Content.End;
        Range rng = doc.Range(ref docStart, ref docEnd);
       // object pageBreak = WdBreakType.wdPageBreak;
        object pageBreak = WdBreakType.wdSectionBreakNextPage;

        rng.InsertBreak(ref pageBreak);
    }
}
内部静态类文档合并{
缺少私有静态对象=类型。缺少;
私有静态应用程序类wordApplication{get;set;}
私有静态void addDocument(对象路径、文档文档、bool firstDocument){
对象子路径=路径;
var subDoc=wordApplication.Documents.Open(引用子文档路径、引用缺失、引用缺失、引用缺失、引用缺失、引用缺失、引用缺失、引用缺失、引用缺失、引用缺失、引用缺失、引用缺失);
试一试{
如果(!firstDocument){
insertPageBreak(doc);
}
对象docStart=doc.Content.End-1;
对象docEnd=doc.Content.End;
对象开始=subDoc.Content.start;
对象端=subDoc.Content.end;
范围rng=单据范围(参考单据开始,参考单据结束);
rng.FormattedText=子文档范围(参考开始,参考结束);
//如果(!lastDocument){
//}
}最后{
子文档关闭(引用缺失、引用缺失、引用缺失);
}
}
公共静态bool deleteFile(字符串文件名){
if(File.Exists(fileName)){
试一试{
删除(文件名);
if(File.Exists(fileName)){
返回false;
}
返回true;
}捕获(IOException){
DialogResult=MessageBox.Show(新形式{TopMost=true},“Plik”+文件名+“jest w użyciu lub nie masz uprawnieńdo zapisania raportu w tym miejscu.Czy chcesz spróbowaćponownie?”,“Błd zapisu(000002)”,MessageBoxButtons.YesNo,MessageBoxIcon.Stop);
if(result==DialogResult.No){
返回false;
}
如果(删除文件(文件名)){
返回true;
}
}捕获(例外e){
MessageBox.Show(新形式{TopMost=true},“Plik”+文件名+“nie może zostaćskasowany.Błąd”+Environment.NewLine+Environment.NewLine+e,“Błd zapisu(000003)”,MessageBoxButtons.YesNo,MessageBoxIcon.Stop);
返回false;
}
}否则{
返回true;
}
返回false;
}
公共静态无效文档合并(对象文件名,列表数组列表){
//对象文件名=Path.Combine(Environment.CurrentDirectory,@“NewDocument.doc”);
bool varTest=deleteFile(fileName.ToString());
if(varTest){
试一试{
wordApplication=newapplicationclass();
var doc=wordApplication.Documents.Add(ref缺失、ref缺失、ref缺失、ref缺失);
试一试{
doc.Activate();
整数计数=0;
foreach(arrayList中的var alItem){
addDocument(alItem,doc,count==0);
计数++;
}
//addDocument(@“D:\Projects\WordTests\ConsoleApplication1\Documents\Doc1.doc”,doc);/,false);
//addDocument(@“D:\Projects\WordTests\ConsoleApplication1\Documents\Doc2.doc”,doc);/,true);
文件保存为(引用文件名、引用缺失、引用缺失、引用缺失、引用缺失、引用缺失、引用缺失、引用缺失、引用缺失、引用缺失、引用缺失、引用缺失、引用缺失、引用缺失、引用缺失、引用缺失);
}最后{
单据关闭(参考缺失、参考缺失、参考缺失);
}
}最后{
wordApplication.Quit(ref缺失,ref缺失,ref缺失);
}
}否则{
返回;
}
}
私有静态void insertPageBreak(文档文档){
对象docStart=doc.Content.End-1;
对象docEnd=doc.Content.End;
范围rng=单据范围(参考单据开始,参考单据结束);
//对象pageBreak=WdBreakType.wdPageBreak;
对象pageBreak=WdBreakType.wdSectionBreakNextPage;
rng.插入中断(参考页面中断);
}
}
看看这个

更改此行:

object pageBreak = Word.WdBreakType.wdPageBreak;
对此

object pageBreak = Word.WdBreakType.wdSectionBreakNextPage;
从第二个文档中获取标题和页脚

添加整个方法,以及在源更改时如何调用它

班级:

using System;
using Word = Microsoft.Office.Interop.Word;
using System.Configuration;

namespace KeithRull.Utilities.OfficeInterop
{
  public class MsWord
  {
    /// <summary>
    /// This is the default Word Document Template file. I suggest that you point this to the location
    /// of your Ms Office Normal.dot file which is usually located in your Ms Office Templates folder.
    /// If it does not exist, what you could do is create an empty word document and save it as Normal.dot.
    /// </summary>
    private static string defaultWordDocumentTemplate = @"Normal.dot";

    /// <summary>
    /// A function that merges Microsoft Word Documents that uses the default template
    /// </summary>
    /// <param name="filesToMerge">An array of files that we want to merge</param>
    /// <param name="outputFilename">The filename of the merged document</param>
    /// <param name="insertPageBreaks">Set to true if you want to have page breaks inserted after each document</param>
    public static void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks)
    {
        Merge(filesToMerge, outputFilename, insertPageBreaks, defaultWordDocumentTemplate);
    }

    /// <summary>
    /// A function that merges Microsoft Word Documents that uses a template specified by the user
    /// </summary>
    /// <param name="filesToMerge">An array of files that we want to merge</param>
    /// <param name="outputFilename">The filename of the merged document</param>
    /// <param name="insertPageBreaks">Set to true if you want to have page breaks inserted after each document</param>
    /// <param name="documentTemplate">The word document you want to use to serve as the template</param>
    public static void Merge(string[] filesToMerge, string outputFilename, bool insertPageBreaks, string documentTemplate)
    {
        object defaultTemplate = documentTemplate;
        object missing = System.Type.Missing;
        object pageBreak = Word.WdBreakType.wdSectionBreakNextPage;
        object outputFile = outputFilename;

        // Create  a new Word application
        Word._Application wordApplication = new Word.Application( );

        try
        {
            // Create a new file based on our template
            Word.Document wordDocument = wordApplication.Documents.Add(
                                          ref missing
                                        , ref missing
                                        , ref missing
                                        , ref missing);

            // Make a Word selection object.
            Word.Selection selection = wordApplication.Selection;

            //Count the number of documents to insert;
            int documentCount = filesToMerge.Length;

            //A counter that signals that we shoudn't insert a page break at the end of document.
            int breakStop = 0;

            // Loop thru each of the Word documents
            foreach (string file in filesToMerge)
            {
                breakStop++;
                // Insert the files to our template
                selection.InsertFile(
                                            file
                                        , ref missing
                                        , ref missing
                                        , ref missing
                                        , ref missing);

                //Do we want page breaks added after each documents?
                if (insertPageBreaks && breakStop != documentCount)
                {
                    selection.InsertBreak(ref pageBreak);
                }
            }

            // Save the document to it's output file.
            wordDocument.SaveAs(
                            ref outputFile
                        , 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);

            // Clean up!
            wordDocument = null;
        }
        catch (Exception ex)
        {
            //I didn't include a default error handler so i'm just throwing the error
            throw ex;
        }
        finally
        {
            // Finally, Close our Word application
            wordApplication.Quit(ref missing, ref missing, ref missing);
        }
    }
}
}

您是否尝试过在xml级别进行合并?Docx是包含Xml文件的zip文件

您可以使用XDocument来合并XML。

从C代码开始,稍微修改一下,使其可以处理页眉和页脚

Eric White的博客解释了代码是如何工作的。

因为合并工作正常。因此,现在可以直接使用DocX而不是使用互操作。唯一需要知道的是
页眉/页脚
取自第一个文档(模板),因为页眉/页脚是按文档而不是按页面设置的

public static void documentsMerge(object fileName, List<string> arrayList) {

        bool varTest = deleteFile(fileName.ToString());
        if (varTest)
        {
            using (DocX documentToCreate = DocX.Load(arrayList[0]))
            {


                foreach (var alItem in arrayList.Skip(1))
                {
                    documentToCreate.InsertParagraph().InsertPageBreakAfterSelf();
                    DocX documentToMergeIn = DocX.Load(alItem);
                    documentToCreate.InsertDocument(documentToMergeIn);
                }
                documentToCreate.SaveAs(fileName.ToString());
            }
        }
    }
publicstaticvoiddocumentsmerge(对象文件名,列表数组列表){
bool varTest=deleteFile(fileName.ToString());
if(varTest)
{
使用(DocX documentToCreate=DocX.Load(arrayList[0]))
public static void documentsMerge(object fileName, List<string> arrayList) {

        bool varTest = deleteFile(fileName.ToString());
        if (varTest)
        {
            using (DocX documentToCreate = DocX.Load(arrayList[0]))
            {


                foreach (var alItem in arrayList.Skip(1))
                {
                    documentToCreate.InsertParagraph().InsertPageBreakAfterSelf();
                    DocX documentToMergeIn = DocX.Load(alItem);
                    documentToCreate.InsertDocument(documentToMergeIn);
                }
                documentToCreate.SaveAs(fileName.ToString());
            }
        }
    }