2012-05-20 46 views
2

將多個XPS文檔合併爲一個時遇到問題。當我合併它們時,結果xps包含重複的最後一個XPS文檔。這裏是我的功能合併(Modified version of this question):合併xps文檔使最後一個重複

public XpsDocument CreateXPSStream(List<XpsDocument> ListToMerge) 
    { 
     var memoryStream = new MemoryStream(); 
     Package container = Package.Open(memoryStream, FileMode.Create); 
     string pack = "pack://temp.xps"; 
     PackageStore.RemovePackage(new Uri(pack)); 
     PackageStore.AddPackage(new Uri(pack), container); 

     XpsDocument xpsDoc = new XpsDocument(container, CompressionOption.SuperFast, "pack://temp.xps"); 
     FixedDocumentSequence seqNew = new FixedDocumentSequence(); 
     foreach (var sourceDocument in ListToMerge) 
     { 
      FixedDocumentSequence seqOld = sourceDocument.GetFixedDocumentSequence(); 
      foreach (DocumentReference r in seqOld.References) 
      { 
       DocumentReference newRef = new DocumentReference(); 
       ((IUriContext)newRef).BaseUri = ((IUriContext)r).BaseUri; 
       newRef.Source = r.Source; 
       seqNew.References.Add(newRef); 
      } 
     } 
     XpsDocumentWriter xpsWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc); 
     xpsWriter.Write(seqNew); 
     //xpsDoc.Close(); 
     //container.Close(); 
     return xpsDoc; 
    } 

結果去的DocumentViewer並顯示給用戶。

回答

8

我創建了以下功能,它適用於我。

public void MergeXpsDocument(string newFile, List<XpsDocument> sourceDocuments) 
    { 
     if (File.Exists(newFile)) 
     { 
      File.Delete(newFile); 
     } 

     XpsDocument xpsDocument = new XpsDocument(newFile, System.IO.FileAccess.ReadWrite); 
     XpsDocumentWriter xpsDocumentWriter = XpsDocument.CreateXpsDocumentWriter(xpsDocument); 
     FixedDocumentSequence fixedDocumentSequence = new FixedDocumentSequence(); 

     foreach(XpsDocument doc in sourceDocuments) 
     { 
      FixedDocumentSequence sourceSequence = doc.GetFixedDocumentSequence(); 
      foreach (DocumentReference dr in sourceSequence.References) 
      { 
       DocumentReference newDocumentReference = new DocumentReference(); 
       newDocumentReference.Source = dr.Source; 
       (newDocumentReference as IUriContext).BaseUri = (dr as IUriContext).BaseUri; 
       FixedDocument fd = newDocumentReference.GetDocument(true); 
       newDocumentReference.SetDocument(fd); 
       fixedDocumentSequence.References.Add(newDocumentReference); 
      } 
     } 
     xpsDocumentWriter.Write(fixedDocumentSequence); 
     xpsDocument.Close(); 
    } 
+0

其他樣品我見過從多個源XPS文檔提取頁面,創建其文檔序列包括含有從源文件所有頁面的單個固定文檔一個新的XPS文件。這是我發現的將新的FixedDocument對象添加到FixedDocumentSequence的唯一示例。 –

+0

工作就像一個魅力。謝謝! –