【问题标题】:How to edit bookmarks in a Word template using DocumentFormat.OpenXml and save it as a new PDF file?如何使用 DocumentFormat.OpenXml 编辑 Word 模板中的书签并将其保存为新的 PDF 文件?
【发布时间】:2016-09-23 02:41:54
【问题描述】:

我在使用 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 方法不起作用。我正在写流并保存它,因为我认为如果书签被替换,那么我可以将它保存到另一个文件中。

【问题讨论】:

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


    【解决方案1】:

    我认为您想确保当您引用 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 添加了密码加密和嵌入水印。

    【讨论】:

    • 我找不到任何关于使用 itextSharp 将 Docx 转换为 PDF 的代码,你能分享一下吗?
    • 当然。给我几分钟
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-26
    • 1970-01-01
    • 2016-05-13
    • 2016-12-17
    • 2016-01-18
    • 1970-01-01
    相关资源
    最近更新 更多