Issues printing PDF files with more than 1 page

Dino Martin Monteclaro 20 Reputation points
2023-02-10T03:26:31.16+00:00

I followed some of Microsoft's sample when printing using the Print Manager interface. It works fine when printing 1 page PDF files, however, if multi page PDF files are rendered, it will only display the last page in the Print Manager preview and prints the same data when processing the print job. Here's my current code that processes all print events.

 private void PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
        {
            PrintTask printTask = null;

            printTask = args.Request.CreatePrintTask("KYOCERA Print Center", sourceRequested =>
            {
                PrintTaskOptionDetails printDetailedOptions = PrintTaskOptionDetails.GetFromPrintTaskOptions(printTask.Options);

                // Choose the printer options to be shown.
                // The order in which the options are appended determines the order in which they appear in the UI
                printDetailedOptions.DisplayedOptions.Clear();
                printDetailedOptions.DisplayedOptions.Add(Windows.Graphics.Printing.StandardPrintTaskOptions.MediaSize);
                printDetailedOptions.DisplayedOptions.Add(Windows.Graphics.Printing.StandardPrintTaskOptions.Copies);

                // Set default orientation to landscape.
                printTask.Options.Orientation = PrintOrientation.Portrait;

                // Set duplex values
                printTask.Options.Duplex = PrintDuplex.Default;

                sourceRequested.SetSource(printDocSource);
            });
        }

        private void Paginate(object sender, PaginateEventArgs e)
        {
            try
            {
                PrintDocument printDoc = (PrintDocument)sender;

                // A new "session" starts with each paginate event.
                Interlocked.Increment(ref requestCount);

                PageDescription pageDescription = new PageDescription();

                // Get printer's page description.
                PrintTaskOptionDetails printDetailedOptions = PrintTaskOptionDetails.GetFromPrintTaskOptions(e.PrintTaskOptions);
                PrintPageDescription printPageDescription = e.PrintTaskOptions.GetPageDescription(0);

                // Compute the printing page description (page size & center printable area)
                pageDescription.PageSize = printPageDescription.PageSize;

                pageDescription.Margin.Width = Math.Max(printPageDescription.ImageableRect.Left,
                                                        printPageDescription.ImageableRect.Right - printPageDescription.PageSize.Width);

                pageDescription.Margin.Height = Math.Max(printPageDescription.ImageableRect.Top,
                                                         printPageDescription.ImageableRect.Bottom - printPageDescription.PageSize.Height);

                if (pageDescription.Margin.Width < printPageDescription.PageSize.Width * 0.05)
                    pageDescription.Margin.Width = printPageDescription.PageSize.Width * 0.05;

                if (pageDescription.Margin.Height < printPageDescription.PageSize.Height * 0.08)
                    pageDescription.Margin.Height = printPageDescription.PageSize.Height * 0.08;


                pageDescription.ViewablePageSize.Width = printPageDescription.PageSize.Width - pageDescription.Margin.Width * 2;
                pageDescription.ViewablePageSize.Height = printPageDescription.PageSize.Height - pageDescription.Margin.Height * 2;

                // Compute print photo area.
                pageDescription.PictureViewSize.Width = pageDescription.ViewablePageSize.Width;
                pageDescription.PictureViewSize.Height = pageDescription.ViewablePageSize.Height;

                pageDescription.IsContentCropped = false;

                // Recreate content only when : 
                // - there is no current page description
                // - the current page description doesn't match the new one
                if (currentPageDescription == null || !currentPageDescription.Equals(pageDescription))
                {
                    if (pageDescription.PictureViewSize.Width > pageDescription.ViewablePageSize.Width ||
                        pageDescription.PictureViewSize.Height > pageDescription.ViewablePageSize.Height)
                    {

                        var str = loader.GetString("litImageWontFitOnPaper");
                        printDetailedOptions.Options["photoSize"].ErrorText = str;

                        // Inform preview that it has only 1 page to show.
                        printDoc.SetPreviewPageCount(1, PreviewPageCountType.Intermediate);

                    }
                    else
                    {
                        // Inform preview that is has #NumberOfPhotos pages to show.
                        printDoc.SetPreviewPageCount(5, PreviewPageCountType.Final);
                    }

                    currentPageDescription = pageDescription;
                }
            }
            catch (Exception) { }
        }

        private async void GetPreviewPage(object sender, GetPreviewPageEventArgs e)
        {
            pagesToPrint = await GeneratePage(currentPageDescription);

            PrintDocument printDoc = (PrintDocument)sender;

            foreach (var pages in pagesToPrint)
            {
                printDoc.SetPreviewPage(e.PageNumber, pages);
            }
        }

        private void AddPages(object sender, AddPagesEventArgs e)
        {
            PrintDocument printDoc = (PrintDocument)sender;

            foreach (var pages in pagesToPrint)
            {
                printDoc.AddPage(pages);
            }
            printDoc.AddPagesComplete();
        }

        private async Task<List<UIElement>> GeneratePage(PageDescription pageDescription)
        {
            List<BitmapImage> bitmapImages = new List<BitmapImage>();
            List<UIElement> pages = new List<UIElement>();

            Canvas page = new Canvas
            {
                Width = pageDescription.PageSize.Width,
                Height = pageDescription.PageSize.Height
            };

            Canvas viewablePage = new Canvas()
            {
                Width = pageDescription.ViewablePageSize.Width,
                Height = pageDescription.ViewablePageSize.Height
            };

            viewablePage.SetValue(Canvas.LeftProperty, pageDescription.Margin.Width);
            viewablePage.SetValue(Canvas.TopProperty, pageDescription.Margin.Height);

            // The image "frame" which also acts as a viewport
            Grid photoView = new Grid
            {
                Width = pageDescription.PictureViewSize.Width,
                Height = pageDescription.PictureViewSize.Height
            };

            // Center the frame.
            photoView.SetValue(Canvas.LeftProperty, (viewablePage.Width - photoView.Width) / 2);
            photoView.SetValue(Canvas.TopProperty, (viewablePage.Height - photoView.Height) / 2);

            StorageFile file = SelectedFile;

            var bitmap = new BitmapImage();

            if (Path.GetExtension(selectedFile.Path).Equals(".xlsx") ||
                Path.GetExtension(selectedFile.Path).Equals(".xls"))
            {
                bitmapImages = await ConvertPdfToBitmap(storageFileToPdf);
                bitmap = null;
            }
            else if (Path.GetExtension(selectedFile.Path).Equals(".pptx") ||
                        Utils.IsDocFileFormatSupported(selectedFile.Path))
            {
                bitmapImages = await ConvertPdfToBitmap(storageFileToPdf);
                bitmap = null;
            }
            else
            {
                bitmap.SetSource(await file.OpenAsync(FileAccessMode.Read));
            }

            if (bitmap != null)
            {
                Image image = new Image
                {
                    Source = bitmap,
                    HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center,
                    VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center
                };

                // Use the real image size when croping or if the image is smaller then the target area (prevent a scale-up).
                if ((bitmap.PixelWidth <= pageDescription.PictureViewSize.Width &&
                    bitmap.PixelHeight <= pageDescription.PictureViewSize.Height))
                {
                    image.Stretch = Stretch.None;
                    image.Width = bitmap.PixelWidth;
                    image.Height = bitmap.PixelHeight;
                }
                photoView.Children.Add(image);
                viewablePage.Children.Add(photoView);
                page.Children.Add(viewablePage);
                pages.Add(page);
            }
            else
            {
                foreach(var btm in bitmapImages)
                {
                    photoView.Children.Clear();
                    viewablePage.Children.Clear();
                    page.Children.Clear();

                    Image image = new Image
                    {
                        Source = btm,
                        HorizontalAlignment = Windows.UI.Xaml.HorizontalAlignment.Center,
                        VerticalAlignment = Windows.UI.Xaml.VerticalAlignment.Center
                    };

                    // Use the real image size when croping or if the image is smaller then the target area (prevent a scale-up).
                    if ((btm.PixelWidth <= pageDescription.PictureViewSize.Width &&
                        btm.PixelHeight <= pageDescription.PictureViewSize.Height))
                    {
                        image.Stretch = Stretch.None;
                        image.Width = btm.PixelWidth;
                        image.Height = btm.PixelHeight;
                    }
                    photoView.Children.Add(image);
                    viewablePage.Children.Add(photoView);
                    page.Children.Add(viewablePage);
                    pages.Add(page);
                }
            }
            return pages;
        }

May I ask why the issue occurs when printing more than 1 PDF file? :(

Universal Windows Platform (UWP)
{count} votes

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.