Convert Wpf form to Pdf report

Jeff Wei 6 Reputation points
2020-06-15T02:45:49.347+00:00

Dear Sirs:

We have a WPF application which display a complex form for a medical data record. User can also click a button to convert the form into the Pdf format for further reading. The current implementation is a two steps conversion which is to to convert it to .XPS first and then convert from Xps to .Pdf.

Unfortunately converting from Wpf form to Xps is a lengthy procedure. Which always takes more than 30 seconds to complete. is there any more efficient way for this conversion? We are using the very formal code as below.

        using (var mem = new MemoryStream())
        using (var pkg = Package.Open(mem, FileMode.Create, FileAccess.ReadWrite))
        using (XpsDocument xpsDoc = new XpsDocument(pkg))
        {
            XpsDocumentWriter xpsWriter = XpsDocument.CreateXpsDocumentWriter(xpsDoc);
            MyDocumentPaginator paginator = new MyDocumentPaginator(listVisual, pageSize, false);
            paginator.ComputePageCount();
            for (int i = 0; i < paginator.PageCount; i++)
            {
                var p = paginator.GetPage(i);
                if (p == null)
                    continue;
                var x = p.Visual;
                if (x is Canvas)
                {
                    var canvas = x as Canvas;
                    canvas.Width = pageSize.Width;
                    canvas.Height = pageSize.Height;
                    canvas.UpdateLayout();
                }
            }
            xpsWriter.Write(paginator);
            xpsDoc.Close();
            pkg.Close();
            mem.Seek(0, SeekOrigin.Begin);
            return mem.ToArray();
        }

Best Regards
Jeff Wei

Windows Presentation Foundation
Windows Presentation Foundation
A part of the .NET Framework that provides a unified programming model for building line-of-business desktop applications on Windows.
2,691 questions
{count} vote

1 answer

Sort by: Most helpful
  1. Jeff Wei 6 Reputation points
    2020-06-16T06:25:47.823+00:00

    Dear Sirs

    The converted Pdf file is generally small. Ranged from 2M to 10M normally. The conversion from Wpf to .Xps is lengthy, while it is quicker to convert the .Xps to .Pdf.

    Best Regards
    Jeff WEI