簡體   English   中英

如何使用DocumentFormat.OpenXml在Word模板中編輯書簽並將其另存為新的PDF文件?

[英]How to edit bookmarks in a Word template using DocumentFormat.OpenXml and save it as a new PDF file?

我在使用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方法不起作用。 我正在寫流並保存它,因為我認為如果書簽被替換,那么我可以將它保存到另一個文件。

我想你要確保當你引用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添加了密碼加密和嵌入水印。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM