Share via

How to Print a PDF File in C# WPF

Kamyab Faghih 70 Reputation points
2024-08-12T03:03:17.3833333+00:00

Hello everyone , I have a PDF file with several pages and I need to print it using C# and WPF technology. Can someone provide some guidance on how to achieve this and customize the settings, such as page size, orientation, and margin? Thank you.

Developer technologies | Windows Presentation Foundation
Developer technologies | C#
Developer technologies | C#

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.


Answer accepted by question author

Anonymous
2024-08-13T09:52:56.8666667+00:00

Hi,@Kamyab Faghih. Welcome to Microsoft Q&A. 

Operation effect.

Original PDF:

Picture1Picture2

Picture3

   

Adjusted PDF:

 Picture4

Picture5Picture6

 

Take WPF App (.NET Framework) as an example.

 

Required

Reference System.Drawing(References->Add References…->Assemblies->Framework-> System.Drawing.).

References Windows.winmd (C:\Program Files (x86)\Windows Kits\10\UnionMetadata\10.0.19041.0\Windows.winmd).

References System.Runtime.WindowsRuntime(Via NuGet).

 

Code


using System;

using System.Collections.Generic;

using System.Drawing.Printing;

using System.Drawing;

using System.IO;

using System.Threading.Tasks;

using System.Windows;

 

    public partial class MainWindow : Window

    {

        public MainWindow()

        {

            InitializeComponent();

            string Path = " The location of your pdf";

            PrintFun(Path);

        }

 

        public async void PrintFun(string Path)

        {

 

            var images = await PdfToImage(Path);

            int i = 0;

            int pages = images.Count;

 

            PrintDocument printDocument = new PrintDocument();

 

 

            printDocument.PrintPage += (sender, e) =>

            {

                System.Drawing.Image image = images[i];

                float scaleX = 1;

                float scaleY = 1;

                float leftMargin = 0;

                float topMargin = 0;

 

 

                //Rotate the second page 180 degrees

                if (i == 1)

                {

                    image.RotateFlip(RotateFlipType.Rotate180FlipNone); // Rotate clockwise by 180 degrees               

                }

 

                //Adjust spacing and scaling for the third page

                if (i == 2)

                {

                    scaleX = 2;

                    scaleY = 2;

                    leftMargin = Convert.ToInt32((e.MarginBounds.Left) * 3 / 4);

                    topMargin = Convert.ToInt32((e.MarginBounds.Left) * 2 / 3);

                }

 

 

                int imageWidth = image.Width;

                int imageHeight = image.Height;

 

                // Calculate the scaling factor to fit the image within the page size

                float X = (float)e.PageSettings.PaperSize.Width / imageWidth;

                float Y = (float)e.PageSettings.PaperSize.Height / imageHeight;

                float scaleFactor = Math.Min(X, Y);

 

                // Draw the image on the page

                e.Graphics.DrawImage(image, leftMargin , topMargin, imageWidth * scaleFactor * scaleX, imageHeight * scaleFactor * scaleY);

                i++;

                if (i < pages)

                {

                    e.HasMorePages = true;  //When true, the method bound to printDocument.PrintPage will be called again

                    image.Dispose();

                    return;

                }

                e.HasMorePages = false;

                image.Dispose();

            };

 

            printDocument.Print();

           

        }

 

 

 

        public async Task<List<System.Drawing.Image>> PdfToImage(string Path)

        {

            var storagePdfFile = await Windows.Storage.StorageFile.GetFileFromPathAsync(Path);

            Windows.Data.Pdf.PdfDocument pdfDocument = await Windows.Data.Pdf.PdfDocument.LoadFromFileAsync(storagePdfFile);

            uint Index = 0;

            List<System.Drawing.Image> images = new List<System.Drawing.Image>();

            while (Index < pdfDocument.PageCount)

            {

                using (Windows.Data.Pdf.PdfPage pdfPage = pdfDocument.GetPage(Index))

                {

                    using (Windows.Storage.Streams.InMemoryRandomAccessStream memStream = new Windows.Storage.Streams.InMemoryRandomAccessStream())

                    {

                        Windows.Data.Pdf.PdfPageRenderOptions pdfPageRenderOptions = new Windows.Data.Pdf.PdfPageRenderOptions();

                        await pdfPage.RenderToStreamAsync(memStream);

                        System.Drawing.Image image = System.Drawing.Image.FromStream(memStream.AsStream());

                        images.Add(image);

                    }

                }

                Index++;

            }

            return images;

        }

    }

 

The code here adjusts the printing of the last two pages.


                //Rotate the second page 180 degrees

                if (i == 1)

                {

                    image.RotateFlip(RotateFlipType.Rotate180FlipNone); // Rotate clockwise by 180 degrees               

                }

 

                //Adjust spacing and scaling for the third page

                if (i == 2)

                {

                    scaleX = 2;

                    scaleY = 2;

                    leftMargin = Convert.ToInt32((e.MarginBounds.Left) * 3 / 4);

                    topMargin = Convert.ToInt32((e.MarginBounds.Left) * 2 / 3);

                }

 


If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

Was this answer helpful?


1 additional answer

Sort by: Most helpful
  1. Castorix31 91,871 Reputation points
    2024-08-12T06:46:16.41+00:00

    Was this answer helpful?


Your answer

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