Printing an existing PDF file generates an error

I am trying to print some existing pdf files of drawings. These pdf files may have multiple pages and each page may be a different size; Letter, Tabloid, ANSI C, ANSI D, etc.

The process I go through is this:

Dim MyPrintServer as PrintServer = new PrintServer

  1. I create a PdfDocument
    Dim PDFDocumentObj as PdfDocument = PdfDocument.Load(FileToPrint)

  2. I iterate through each page of the document to determine what size it is and set my print settings accordingly.

For PageCount = 1 to PDFDocumentObj.Pages.Count
      Dim MyPrintQueue as PrintQueue = MyPrintServer.GetPrintQueue(PrinterToUse)
      Dim PDFPageObj as PDFPage = PDFDocumentObj.Pages.Item(PageCount - 1)
      Dim MyPrintTicket as PrintTicket = MyPrintQueue.DefaultPrintTicket
      MyPrintTicket.PageMediaSize = New PageMediaSize(PDFPageObj.Size.Width, PDFPageObj.Size.Height)
      Dim MyPrintOptions as PrintOptions = New PrintOptions(MyPrintTicket.GetXmlStream)
      MyPrintOptions.DocumentName = FileName & "-" & PageCount.ToString
      MyPrintOptions.FromPage = PageCount
      MyPrintOptions.ToPage = PageCount
      MyPrintOptions.CopyCount = NumberOfCopies
               PDFDocumentObj.Print(MyPrintQueue.FullName, MyPrintOptions)
               ReturnedBoolean = True
      Catch ex As Exception
               ReturnedBoolean = False
      End Try

When my code hits the Print statement, it throws an error with the following message:

Value Does Not Fall Within The Expected Range

Could anyone tell me what I am doing wrong? I will admit that I am new to printing in this manner, using PrintTicket and all, so my methodology could be way off.

Thanks in advance,

Darren Haverstick
Paul Mueller Company

Hi Darren,

The problem occurs because the PrintOptions.FromPage and PrintOptions.ToPage are also zero-indexed. In other words, you’ll need to set those to PageCount - 1 (the same as how you’re retrieving from the PDFDocumentObj.Pages collection).

Anyway, GemBox.Pdf will set the media size for each page, so there is no need for you to do that.

I hope this helps.


Thank you, Mario! That fixed the problem.