将页眉和页脚复制到所有其他文档OpenXML [英] Copy Header and Footer to all other Documents OpenXML

查看:153
本文介绍了将页眉和页脚复制到所有其他文档OpenXML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们有一个主docx,其中有页眉和页脚,没有别的(用图像格式化).我们有100个带有正文内容的Word文档,但没有页眉和页脚,我们希望能够在填充它们并从主页眉和页脚docx添加页眉和页脚时进行处理.

We have a master docx with the header and footer in and nothing else (formatted with images). We have 100s of word documents with body content but no header and footer and we want to be able to process these when we populate them and add the header and footer from the master header and footer docx.

我在这里查看了MSDN文档: https://msdn. microsoft.com/en-us/library/cc546917.aspx ,但是它似乎不起作用,当我打开目标文档时,格式错误并且图像丢失.

I have looked at the MSDN documentation here: https://msdn.microsoft.com/en-us/library/cc546917.aspx but it doesn't seem to work and when I open the target document the formatting is wrong and the images are missing.

是否有一种方法可以使页眉和页脚从一个文档准确复制到另一个文档?

Is there a way to make this exactly copy the header and footer from one document to another?

推荐答案

我还必须为工作中的客户端实现此功能. 我将为您提供我为页眉和页脚编写的方法.

I also had to implement this for a client at work. I'll give you the methods I wrote for headers and footers.

我写过尝试将所有样式,字体,尺寸和图像保留在页眉和页脚中.

I wrote trying to keep all styles, fonts, dimensions and images inside header and footer.

这是我用来将标头附加到另一个docx的方法.

This is the method that i use to attach header to another docx.

尝试理解阅读我写的评论.

Try to understand reading the comments I've written.

headerTemplatePath:获取标头的docx路径

headerTemplatePath: path of docx where take header

documentPath:附加标头的docx路径

documentPath: path of docx where append header

    public void PrependHeader(string headerTemplatePath, string documentPath)
    {
        // Open docx where we need to add header
        using (var wdDoc = WordprocessingDocument.Open(documentPath, true))
        {
            var mainPart = wdDoc.MainDocumentPart;

            // Delete exist header
            mainPart.DeleteParts(mainPart.HeaderParts);

            // Create new header
            var headerPart = mainPart.AddNewPart<HeaderPart>();

            // Get id of new header
            var rId = mainPart.GetIdOfPart(headerPart);

            // Open the header document to be copied
            using (var wdDocSource = WordprocessingDocument.Open(headerTemplatePath, true))
            {
                // Get header part
                var firstHeader = wdDocSource.MainDocumentPart.HeaderParts.FirstOrDefault();
                if (firstHeader != null)
                {
                    // Copy content of header to new header
                    headerPart.FeedData(firstHeader.GetStream());
                    // Keep formatting
                    foreach (var childElement in headerPart.Header.Descendants<Paragraph>())
                    {
                        var paragraph = (Paragraph) childElement;
                        if (paragraph.ParagraphProperties.SpacingBetweenLines == null)
                        {
                            paragraph.ParagraphProperties.SpacingBetweenLines = new SpacingBetweenLines
                            {
                                After = "0"
                            };
                            paragraph.ParagraphProperties.ParagraphStyleId = new ParagraphStyleId
                            {
                                Val = "No Spacing"
                            };
                        }
                    }
                    // Get all ids of every 'Parts'
                    var listToAdd = new List<KeyValuePair<Type, Stream>>();
                    foreach (var idPart in firstHeader.Parts)
                    {
                        var part = firstHeader.GetPartById(idPart.RelationshipId);
                        if (part is ImagePart)
                        {
                            headerPart.AddNewPart<ImagePart>("image/png", idPart.RelationshipId);
                            listToAdd.Add(new KeyValuePair<Type, Stream>(typeof (ImagePart), part.GetStream()));
                        }
                        else if (part is DiagramStylePart)
                        {
                            headerPart.AddNewPart<DiagramStylePart>(idPart.RelationshipId);
                            listToAdd.Add(new KeyValuePair<Type, Stream>(typeof (DiagramStylePart), part.GetStream()));
                        }
                        else if (part is DiagramColorsPart)
                        {
                            headerPart.AddNewPart<DiagramColorsPart>(idPart.RelationshipId);
                            listToAdd.Add(new KeyValuePair<Type, Stream>(typeof (DiagramColorsPart),
                                part.GetStream()));
                        }
                        else if (part is DiagramDataPart)
                        {
                            headerPart.AddNewPart<DiagramDataPart>(idPart.RelationshipId);
                            listToAdd.Add(new KeyValuePair<Type, Stream>(typeof (DiagramDataPart), part.GetStream()));
                        }
                        else if (part is DiagramLayoutDefinitionPart)
                        {
                            headerPart.AddNewPart<DiagramStylePart>(idPart.RelationshipId);
                            listToAdd.Add(new KeyValuePair<Type, Stream>(typeof (DiagramStylePart), part.GetStream()));
                        }
                        else if (part is DiagramPersistLayoutPart)
                        {
                            headerPart.AddNewPart<DiagramPersistLayoutPart>(idPart.RelationshipId);
                            listToAdd.Add(new KeyValuePair<Type, Stream>(typeof (DiagramPersistLayoutPart),
                                part.GetStream()));
                        }
                    }
                    // Foreach Part, copy stream to new header
                    var i = 0;
                    foreach (var idPart in headerPart.Parts)
                    {
                        var part = headerPart.GetPartById(idPart.RelationshipId);
                        if (part.GetType() == listToAdd[i].Key)
                        {
                            part.FeedData(listToAdd[i].Value);
                        }
                        i++;
                    }
                }
                else
                {
                    mainPart.DeleteParts(mainPart.HeaderParts);
                    var sectToRemovePrs = mainPart.Document.Body.Descendants<SectionProperties>();
                    foreach (var sectPr in sectToRemovePrs)
                    {
                        // Delete reference of old header
                        sectPr.RemoveAllChildren<HeaderReference>();
                    }
                    return;
                }
            }

            // Get all sections, and past header to each section (Page)
            var sectPrs = mainPart.Document.Body.Descendants<SectionProperties>();
            foreach (var sectPr in sectPrs)
            {
                // Remove old header reference 
                sectPr.RemoveAllChildren<HeaderReference>();
                // Add new header reference
                sectPr.PrependChild(new HeaderReference { Id = rId });
            }
        }
    }

脚步方法:

footerTemplatePath:获取页脚的docx路径

footerTemplatePath: path of docx where take footer

documentPath:附加页脚的docx路径

documentPath: path of docx where append footer

    public void PrependFooter(string footerTemplatePath, string documentPath)
    {
        // Open docx where append footer
        using (var wdDoc = WordprocessingDocument.Open(documentPath, true))
        {
            var mainPart = wdDoc.MainDocumentPart;

            // Remove exist footer
            mainPart.DeleteParts(mainPart.FooterParts);

            // Create new footer
            var footerParts = mainPart.AddNewPart<FooterPart>();

            // Get Id of new footer
            var rId = mainPart.GetIdOfPart(footerParts);

            // Open the footer document to be copied
            using (var wdDocSource = WordprocessingDocument.Open(footerTemplatePath, true))
            {
                var firstFooter = wdDocSource.MainDocumentPart.FooterParts.LastOrDefault();
                if (firstFooter != null)
                {
                    // Copy content of footer
                    footerParts.FeedData(firstFooter.GetStream());
                    // Keep formatting
                    foreach (var childElement in footerParts.Footer.Descendants<Paragraph>())
                    {
                        var paragraph = (Paragraph) childElement;
                        if (paragraph.ParagraphProperties.SpacingBetweenLines == null)
                        {
                            paragraph.ParagraphProperties.SpacingBetweenLines = new SpacingBetweenLines
                            {
                                After = "0"
                            };
                            paragraph.ParagraphProperties.ParagraphStyleId = new ParagraphStyleId
                            {
                                Val = "No Spacing"
                            };
                        }
                    }
                    // Create list of Parts ID needed to new footer
                    var listToAdd = new List<KeyValuePair<Type, Stream>>();
                    foreach (var idPart in firstFooter.Parts)
                    {
                        var part = firstFooter.GetPartById(idPart.RelationshipId);
                        if (part is ImagePart)
                        {
                            footerParts.AddNewPart<ImagePart>("image/png", idPart.RelationshipId);
                            listToAdd.Add(new KeyValuePair<Type, Stream>(typeof (ImagePart), part.GetStream()));
                        }
                        else if (part is DiagramStylePart)
                        {
                            footerParts.AddNewPart<DiagramStylePart>(idPart.RelationshipId);
                            listToAdd.Add(new KeyValuePair<Type, Stream>(typeof (DiagramStylePart), part.GetStream()));
                        }
                        else if (part is DiagramColorsPart)
                        {
                            footerParts.AddNewPart<DiagramColorsPart>(idPart.RelationshipId);
                            listToAdd.Add(new KeyValuePair<Type, Stream>(typeof (DiagramColorsPart),
                                part.GetStream()));
                        }
                        else if (part is DiagramDataPart)
                        {
                            footerParts.AddNewPart<DiagramDataPart>(idPart.RelationshipId);
                            listToAdd.Add(new KeyValuePair<Type, Stream>(typeof (DiagramDataPart), part.GetStream()));
                        }
                        else if (part is DiagramLayoutDefinitionPart)
                        {
                            footerParts.AddNewPart<DiagramStylePart>(idPart.RelationshipId);
                            listToAdd.Add(new KeyValuePair<Type, Stream>(typeof (DiagramStylePart), part.GetStream()));
                        }
                        else if (part is DiagramPersistLayoutPart)
                        {
                            footerParts.AddNewPart<DiagramPersistLayoutPart>(idPart.RelationshipId);
                            listToAdd.Add(new KeyValuePair<Type, Stream>(typeof (DiagramPersistLayoutPart),
                                part.GetStream()));
                        }
                    }
                    // Foreach ID, copy stream to new footer
                    var i = 0;
                    foreach (var idPart in footerParts.Parts)
                    {
                        var part = footerParts.GetPartById(idPart.RelationshipId);
                        if (part.GetType() == listToAdd[i].Key)
                        {
                            part.FeedData(listToAdd[i].Value);
                        }
                        i++;
                    }
                }
                else
                {
                    mainPart.DeleteParts(mainPart.FooterParts);
                    var sectToRemovePrs = mainPart.Document.Body.Descendants<SectionProperties>();
                    foreach (var sectPr in sectToRemovePrs)
                    {
                        // Delete reference of footer
                        sectPr.RemoveAllChildren<FooterReference>();
                    }
                    return;
                }
            }

            // Get all sections, and past footer to each section (Page)
            var sectPrs = mainPart.Document.Body.Descendants<SectionProperties>();
            foreach (var sectPr in sectPrs)
            {
                // Delete old reference
                sectPr.RemoveAllChildren<FooterReference>();
                // Add new footer reference
                sectPr.PrependChild(new FooterReference { Id = rId });
            }
        }
    }

对不起,我的英语,如果您有任何疑问,请告诉我.

Sorry for my English, if you have any questions, let me know.

再见.

这篇关于将页眉和页脚复制到所有其他文档OpenXML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆