-2

I am trying to print a pdf document and save it to a file when I receive the prompt to save the document. The file is generated with the right number of pages but all pages are blank. What am I missing in the PrintPage handler below? Thanks for any advice.

var ctrl = new StandardPrintController();

using (PrintDocument doc = new PrintDocument())
    {
        doc.PrintController = ctrl;
        doc.PrinterSettings.PrinterName = "CutePDF Writer";
        doc.PrinterSettings.PrintFileName = fileName;

        doc.PrintPage += (s, e) =>
        {
            pageNo++;
            if (pageNo < frameCount)
            {
                e.HasMorePages = true;
            }
            else
            {
                e.HasMorePages = false;
            }
        };

        doc.Print();
    }
NineBerry
  • 20,173
  • 3
  • 50
  • 78
Jyina
  • 2,042
  • 7
  • 35
  • 67
  • 1
    There is no code that draws anything onto the pages. – NineBerry Jul 23 '19 at 16:11
  • Any idea how to draw pdf pages? Thanks. – Jyina Jul 23 '19 at 16:24
  • Why would you want to print to a pdf when you already have a pdf? – NineBerry Jul 23 '19 at 16:27
  • The original pdf is an optimized pdf generated from an open source library. I need to send it to print pdf and save the file to deoptimize the original pdf. – Jyina Jul 23 '19 at 16:48
  • 1
    It is not clear what you mean with "optimized" and "deoptimize". But whatever you want to do is probably much easier achieved by using a pdf library for .net to make the changes in the pdf directly rather than go through some print process. – NineBerry Jul 24 '19 at 08:01

1 Answers1

0

If you want to print the pdf, you can use PdfiumViewer an open source library.

Link to Nuget package:

https://www.nuget.org/packages/PdfiumViewer/

Then modify your code to load the document you want to print:

        var ctrl = new StandardPrintController();

        using (var document = PdfDocument.Load(filename))
        {
            using (PrintDocument doc = document.CreatePrintDocument())
            {
                doc.PrintController = ctrl;
                doc.PrinterSettings.PrinterName = "CutePDF Writer";
                doc.PrinterSettings.PrintFileName = fileName;

                doc.PrintPage += (s, e) =>
                {
                    pageNo++;
                    if (pageNo < frameCount)
                    {
                        e.HasMorePages = true;
                    }
                    else
                    {
                        e.HasMorePages = false;
                    }
                };

                doc.Print();
            }
        }
    }
}