4

我在使用 Word 模板编辑书签Document.Format.OpenXML然后将其保存到新的 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方法不起作用。我正在编写流并保存它,因为我认为如果书签被替换,那么我可以将它保存到另一个文件中。

4

1 回答 1

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 中添加了密码加密和嵌入水印。

于 2016-05-25T14:45:40.800 回答