Parys Bernard
Parys Bernard

Reputation: 159

WPF convert XPS with multiple pages to PDF

I Have a WPF application where I create a XPS document (from Excel) and then I'm able to convert the XPS document to a PDF file:

PdfSharp.Xps.XpsConverter.Convert(sourceXpsFile, destPdfFile, 0);

But when my XPS document contains multiple pages then only the first page is converted to PDF.

It seems like my XPS file is wrong, I create multiple single XPS file and then I merge them with:

public void MergeXpsDocument(string newFile, List<XpsDocument> sourceDocuments)
    {
        Thread th = new Thread(() =>
        {    
            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);

                }
                doc.Close();
            }
            xpsDocumentWriter.Write(fixedDocumentSequence);
            xpsDocument.Close();
        });
        th.SetApartmentState(ApartmentState.STA);
        th.Start();
    }

Maybe I should use another way to merge my XPS files?

Upvotes: 1

Views: 1648

Answers (1)

Parys Bernard
Parys Bernard

Reputation: 159

There was an issue with the methode to merge my XPS documents, I change it to the code found here: Can multiple xps documents be merged to one in WPF?

Now I'm able to convert all pages to PDF.

Upvotes: 2

Related Questions