2014-09-05 32 views
0

從Word文檔複製內容到另一個Word文檔時遇到了一些問題。 信息應該以最終結尾的文檔具有標題。如何將Word Document中的內容與圖像和鏈接複製到一起?

到目前爲止,我已經設法將內容複製到第二個文檔,而不會影響標題。 但是我不知道如何綁定鏈接和圖像的關係。

這是我到目前爲止的代碼:

public static void AddContentToTemplateCopy(
         string sourceDocumentPath, string endDocumentPath) 
{ 
    using (WordprocessingDocument sourceDoc = 
      WordprocessingDocument.Open(sourceDocumentPath, false)) 
    using (WordprocessingDocument endDoc = 
      WordprocessingDocument.Open(endDocumentPath, true)) 
    { 
      var sourceMainPart = sourceDoc.MainDocumentPart; 
      var sourceBody = sourceMainPart.Document.Body; 

      var endSection = endDoc.MainDocumentPart.Document.Body.Elements<SectionProperties>(); 
      var endDocMainPart = endDoc.MainDocumentPart; 
      var sourceBodyClone = sourceBody.CloneNode(true); 
      sourceBodyClone.ReplaceChild(endSection.FirstOrDefault().CloneNode(true), sourceBodyClone.Elements<SectionProperties>().FirstOrDefault()); 
      endDocMainPart.Document.ReplaceChild(sourceBodyClone, endDocMainPart.Document.Body); 

      foreach (HyperlinkRelationship link in sourceMainPart.HyperlinkRelationships) 
      { 
       endDocMainPart.AddHyperlinkRelationship(link.Uri, link.IsExternal, link.Id); 
      } 
} 

我收到以下錯誤:「rId6」與指定源的現有關係的ID衝突。

而如果我有一個圖像的內容,它無法顯示。

如果我壓縮的文件,並期待在包我能找到的圖片文件,但出於同樣的原因的鏈接關係

所以我的問題是:如何綁定的聯繫和帶有「_rels」參考的圖像?或者我如何複製它們以使其正常工作。

這是手動添加鏈接時的關係鏈接。

<Relationship Target="media/image1.jpg" Type="http://schemas.openxmlformats.org/officeDocument/2006/relationships/image" Id="rId11"/> 

用於顯示鏈接文本被複制但沒有格式並且圖像無法顯示的圖片。

enter image description here

回答

1

你可能會發現更容易嘗試埃裏克·懷特的document builder

+0

感謝您的鏈接。你有使用文檔構建器的經驗嗎?你能否更具體地告訴我它是如何工作的圖像和鏈接。也許是一個鏈接?謝謝。 – 2014-09-08 06:44:10

2

感謝JasonPlutext的回答,我設法使用了OpenXML PowerTools (Version 2.2).請記住,在導入項目時.Net版本是3.5。你可能需要改變它。 (支持Open XML 2.5以及我所注意到的)

非常簡單地創建新文檔並從舊文檔中取出零件。

這裏的代碼在我的情況下,我想從一個格式和內容,然後從模板文件的標題。訂單很重要。

希望這會爲其他同樣的問題節省時間。

public static void AddContentToTemplateCopy(string templateDocumentPath, 
              string contentDocumentPath, 
              List<Source> sources, 
              string outName) 
    { 
     sources = new List<Source>() 
     { 
      new Source(new WmlDocument(contentDocumentPath),false), 
      new Source(new WmlDocument(templateDocumentPath),true), 
     }; 
     DocumentBuilder.BuildDocument(sources, outName); 
    }