I'm trying to split an XPS document into other XPS documents. I've used the following code to get started which works fine for a single page but not more (http://stackoverflow.com/questions/5328596/extract-a-single-page-from-an-xps-document). In the code below I'm trying to extract the first 3 pages of the parent document into the child document. Once I'll figure this one out, I'll extract the remaining pages into other documents.
The problem I have is to add the parent's pages to the child, so I tried to create a copy of each page using a memorystream but I now get the following exception when calling the XpsDocumentWriter.
Exception: "I/O error occured".
How should I add the parent's pages to the child?
Resolved: this code works in my WF4 project.
public void Split(InputFile parent, string outputDirectory, int splitPageFrequency, CodeActivityContext context)
{
// Open the parent XPS package
using (Package package = Package.Open(parent.InputFilePath, FileMode.Open, FileAccess.Read))
{
string Pack = "pack://temp.xps";
Uri packageUri = new Uri(Pack);
PackageStore.AddPackage(packageUri, package);
// Get the parent XPS document
XpsDocument xpsDocumentParent = new XpsDocument(package, CompressionOption.Maximum, Pack);
FixedDocumentSequence fixedDocumentSequenceParent = xpsDocumentParent.GetFixedDocumentSequence();
DocumentReference documentReferenceParent = fixedDocumentSequenceParent.References.First();
FixedDocument fixedDocumentParent = documentReferenceParent.GetDocument(false);
for (int pageCounter = 0, fileCounter = 1; pageCounter < fixedDocumentParent.Pages.Count; pageCounter += splitPageFrequency, fileCounter++)
{
// Generate the child file name
Guid documentId = Guid.NewGuid();
string childName = outputDirectory + parent.InputFileId + "_" + fileCounter + "_" + documentId + ".xps";
// Open the child XPS package
using (Package packageDest = Package.Open(childName))
{
// Create the child XPS document
XpsDocument xpsDocumentChild = new XpsDocument(packageDest, CompressionOption.Maximum, childName);
FixedDocument fixedDocumentChild = new FixedDocument();
// Add the parent's pages in range to the child
for (int pageCounterChild = pageCounter; pageCounterChild < pageCounter + splitPageFrequency; pageCounterChild++)
{
// Add the copied fixedpage to the child FixedDocument.
PageContent pageContentChild = new PageContent();
pageContentChild.Source = fixedDocumentParent.Pages[pageCounterChild].Source;
(pageContentChild as IUriContext).BaseUri = ((IUriContext)fixedDocumentParent.Pages[pageCounterChild]).BaseUri;
pageContentChild.GetPageRoot(false);
fixedDocumentChild.Pages.Add(pageContentChild);
}
//Write the child FixedDocument to the XPSdocument
XpsDocumentWriter writer = XpsDocument.CreateXpsDocumentWriter(xpsDocumentChild);
writer.Write(fixedDocumentChild);
xpsDocumentChild.Close();
}
// Set the OutArgument value
NumberOfDocuments.Set(context, fileCounter);
}
PackageStore.RemovePackage(packageUri);
xpsDocumentParent.Close();
}
}