如何使用DocumentFormat.OpenXml在Word模板中编辑书签并将其另存为新的PDF文件?

时间:2016-05-25 13:04:09

标签: c# asp.net ms-word openxml wordprocessingml

我在使用Document.Format.OpenXML在Word模板中编辑书签时遇到了麻烦,然后将其保存到新的PDF文件中。 我无法使用Microsoft.Word.Interop,因为它在服务器上出现COM错误。

我的代码是:

public static void CreateWordDoc(string templatePath, string destinationPath, Dictionary<string, dynamic> dictionary)
{

    byte[] byteArray = File.ReadAllBytes(templatePath);
    using (MemoryStream stream = new MemoryStream())
    {
        stream.Write(byteArray, 0, (int)byteArray.Length);
        using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(stream, true))
        {
            var bookmarks = (from bm in wordDoc.MainDocumentPart.Document.Body.Descendants<BookmarkStart>()
                             select bm).ToList();

            foreach (BookmarkStart mark in bookmarks)
            {

                if (mark.Name != "Table" && mark.Name != "_GoBack")
                {

                 UpdateBookmark(dictionary, mark);//Not doing anything

                }
                else if (mark.Name != "Table")
                {
                    //  CreateTable(dictionary, wordDoc, mark);
                }
            }
           File.WriteAllBytes("D:\\RohitDocs\\newfile_rohitsingh.docx", stream.ToArray());

            wordDoc.Close();

        }
        // Save the file with the new name

    }
}

private static void UpdateBookmark(Dictionary<string, dynamic> dictionary, BookmarkStart mark)
{
    string name = mark.Name;
    string value = dictionary[name];

    Run run = new Run(new Text(value));
    RunProperties props = new RunProperties();

    props.AppendChild(new FontSize() { Val = "20" });
    run.RunProperties = props;
    var paragraph = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(run);
    mark.Parent.InsertAfterSelf(paragraph);

    paragraph.PreviousSibling().Remove();
    mark.Remove();
}

我试图用我的文字替换书签,但UpdateBookmark方法不起作用。我正在编写流并保存它,因为我认为如果替换了书签,那么我可以将其保存到另一个文件中。

1 个答案:

答案 0 :(得分:0)

我认为您希望确保在引用mark.Parent时获得正在获得的正确实例。

一旦您获得了内容应该去的正确Paragraph元素的引用,请使用以下代码添加/交换运行。

// assuming you have a reference to a paragraph called "p"
p.AppendChild<Run>(new Run(new Text(content)) { RunProperties = props });

// and here is some code to remove a run
p.RemoveChild<Run>(run);

为了回答你问题的第二部分,几年前我做了类似的项目,我们使用iTextSharp从Docx创建PDF。它运作良好,API很容易理解。我们甚至为PDF添加了密码加密和嵌入水印。