c#openxml:复制带有字体和对齐方式的段落 [英] c# openxml : copy paragraph with font and alignment

查看:310
本文介绍了c#openxml:复制带有字体和对齐方式的段落的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将单词* .docx的一部分复制到另一个* .docx文件中.为此,我从原始文件中获得了一个段落列表:

I want to copy a part of word *.docx to another *.docx file. For this I get a list of paragraphs from the original file :

private static List<Paragraph> getTextItems( string origFile )
{
    List<Paragraph> paragraphItems = new List<Paragraph>();
    var parser = new LineTextParser();

    using (var doc = WordprocessingDocument.Open( origFile, false))
    {

        foreach (var el in doc.MainDocumentPart.Document.Body.Elements().OfType<Paragraph>())
        {
            if (parser.isHorizontalTableLine(el.InnerText))
            {
                if (true == el.InnerText.EndsWith("|"))
                {
                    break;
                }
            }
            paragraphItems.Add(el);
        }
    }

    return paragraphItems;
}

然后我正尝试将这些项目应用于新文件:

Then I'm trying to apply these items to a new file :

    using (WordprocessingDocument wordDocument =
        WordprocessingDocument.Create(resultFile, WordprocessingDocumentType.Document))
    {
        // Add a main document part. 
        MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

        // Create the document structure and add some text.
        mainPart.Document = new Document();
        Body body = mainPart.Document.AppendChild(new Body());
        foreach (var item in paragraphItems)
        {
            Paragraph para = body.AppendChild(new Paragraph() );
            para.Append(item.ParagraphProperties.CloneNode(true));
            Run run = para.AppendChild(new Run());
            run.AppendChild(new Text(item.InnerText));
        }
    }

但是原始格式丢失了-我的意思是字体已经更改,而且对齐.这里有什么解决方案?

But original formatting is lost - I mean the font has been changed and also alignment. What is the solution here?

推荐答案

首先,使用item.InnerXml代替item.InnerText并将新段落Xml设置为源段落Xml.

First, instead of item.InnerText use item.InnerXml and set the new paragraph Xml to the source paragraph Xml.

您只需要重新排列将段落添加到文档的方式.下面的方法应使用从原始文档复制的段落创建文件.

You just need to re-order the way the paragraphs are being appended to the document. The method below should create the file with the paragraphs copied from the original document.

public void CreateFile(string resultFile, List<Paragraph> paragraphItems)
{
    using (WordprocessingDocument wordDocument =
           WordprocessingDocument.Create(resultFile, WordprocessingDocumentType.Document))
    {
        MainDocumentPart mainPart = wordDocument.AddMainDocumentPart();

        mainPart.Document = new Document();
        Body body = mainPart.Document.AppendChild(new Body());

        foreach (var item in paragraphItems)
        {
            Paragraph para = new Paragraph();

            // set the inner Xml of the new paragraph
            para.InnerXml = item.InnerXml;

            // append paragraph to body here
            body.AppendChild(para);
        }
    }
}

现在,我们需要将doc.MainDocumentPart.StyleDefinitionsPart中的样式应用于新文档.

Now we need to apply the styles from doc.MainDocumentPart.StyleDefinitionsPart to the new document.

此MSDN修改了以下方法指南.它将StyleDefinitionsPart中的样式提取为XDocument.

This following method was modified from this MSDN guide. It extracts the styles from StyleDefinitionsPart as an XDocument.

public XDocument ExtractStylesPart(string sourceFile)
{
    XDocument styles = null;

    // open readonly
    using (var document = WordprocessingDocument.Open(sourceFile, false))
    {
        var docPart = document.MainDocumentPart;

        StylesPart stylesPart = docPart.StyleDefinitionsPart;

        if (stylesPart != null)
        {
            using (var reader = XmlNodeReader.Create(
                       stylesPart.GetStream(FileMode.Open, FileAccess.Read)))
            {
                // Create the XDocument.
                styles = XDocument.Load(reader);
            }
        }
    }
    // Return the XDocument instance.
    return styles;
} 

然后,您需要将样式保存到新文档中.以下方法应为您工作:

Then you need to save the style to the new document. The following method should work for you:

public void SetStyleToTarget(string targetFile, XDocument newStyles)
{
    // open with write permissions
    using (var doc = WordprocessingDocument.Open(targetFile, true))
    {
            // add or get the style definition part
            StyleDefinitionsPart styleDefn = null;
            if (doc.MainDocumentPart.StyleDefinitionsPart == null)
            {
                styleDefn = doc.MainDocumentPart.AddNewPart<StyleDefinitionsPart>();
            }
            else
            {
                styleDefn = doc.MainDocumentPart.StyleDefinitionsPart;
            }

        // populate part with the new styles
        if (styleDefn != null)
        {
            // write the newStyle xDoc to the StyleDefinitionsPart using a streamwriter
            newStyles.Save(new StreamWriter(
                           styleDefn.GetStream(FileMode.Create, FileAccess.Write)));
        }
        // probably not needed (works for me with or without this save)
        doc.Save();
    }
}

上述方法的灵感来自前面链接的指南.不同之处在于,这会为新文档创建一个新的样式元素(因为它没有一个元素-我们只是创建了文档).

The above method was inspired by the guide linked earlier. The difference is that this creates a new style element for the new document (because it doesn't have one - we just created the doc).

我只使用了StyleDefinitionsPart,但是还有另一个部分StylesWithEffectsPart.如果您的文档使用StylesWithEffectsPart,则可能需要实现类似的方法.

I only used StyleDefinitionsPart but there is another part StylesWithEffectsPart. You may need to implement similar method for the StylesWithEffectsPart if your document uses it.

这篇关于c#openxml:复制带有字体和对齐方式的段落的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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