Click here to Skip to main content
14,486,704 members
Rate this:
Please Sign up or sign in to vote.
See more:
Good morning
Please could you tell me how to print a PDF file directly without opening the print dialog box and setting the A4 paper size? As for the first part of my question, actually, I found many examples, I did a class that prints files, but often prints them not in A4 format. So what I would like is to be able to set the A4 format before printing and also test if there are more than one page in the PDF file and possibly print the second page. I tried to see if it can be done with ITextSharp, but I didn't understand if it can do with an existing file.
Thanks a lot for any help you want to give me.
Fabrizio

What I have tried:

Imports Microsoft.VisualBasic
Imports System.Drawing.Printing
Imports System.IO


Public Class StampaPDF

    'CLASSE CHE STAMPA I PDF SENZA APRIRE I FILE

    Public Sub New(ByVal args As String)

        Dim PathDisegni As String = args

        Dim mioPdf As New Pdf
        Dim files() As String = Directory.GetFiles(PathDisegni)

        'Variabile predicate con lambda func con parametri che passa una stringa e ritorna un boolean
        Dim predicate As Func(Of String, Boolean) = Function(file) file.Contains(".pdf")

        For Each file As String In files.Where(predicate)
            mioPdf.PrintPDFs2(file)
        Next

    End Sub

End Class

Public Class Pdf

    'Dichiara i PrinterSetting
    Public Shared defaultPrinterSetting As PrinterSettings = Nothing

    Public Function PrintPDFs(ByVal pdfFileName As String) As Boolean

        Try
            Dim psi As New System.Diagnostics.ProcessStartInfo()
            psi.UseShellExecute = True
            psi.Verb = "print"
            psi.WindowStyle = ProcessWindowStyle.Hidden
            psi.FileName = pdfFileName
            Dim myProcess As System.Diagnostics.Process
            myProcess = System.Diagnostics.Process.Start(psi)
            myProcess.WaitForInputIdle()
            Dim localProces As Diagnostics.Process = Diagnostics.Process.GetProcessById(myProcess.Id)
            localProces.CloseMainWindow()
            localProces.Close()
            Return True
        Catch ex As Exception
            Return False
        End Try

    End Function

    Public Shared Async Function PrintPDFs2(ByVal pdfFileName As String) As Task(Of Boolean)
        Try

            Dim DocPrinter As New DocumentPrinter
            'Ottiene la stampante di default del sistema
            defaultPrinterSetting = Await DocPrinter.GetDefaultPrinterSetting

            'Togliere il commento se si vuole cambiare la stampante di default prima di stampare
            'DocumentPrinter.ChangePrinterSettings(defaultPrinterSetting)

            'Stampa il file 
            If (Await DocPrinter.PrintFile(pdfFileName, defaultPrinterSetting)) Then
                MsgBox("Il Disegno è stato stampato !!")
            Else
                MsgBox("Il Disegno NON è stato stampato !!")
            End If

        Catch ex As Exception
            MsgBox(ex.Message.ToString)
        End Try

    End Function

End Class

Public NotInheritable Class DocumentPrinter

    Shared Sub New()

    End Sub

    Public Shared Async Function PrintFile(ByVal fileName As String, printerSetting As PrinterSettings) As Task(Of Boolean)

        Dim printProcess As Process = Nothing
        Dim printed As Boolean = False

        Try
            If printerSetting IsNot Nothing Then
                Dim startInfo As New ProcessStartInfo()
                startInfo.Verb = "Print"
                startInfo.Arguments = Pdf.defaultPrinterSetting.PrinterName ' <----Stampante da usare---- 
                startInfo.FileName = fileName
                startInfo.UseShellExecute = True
                startInfo.CreateNoWindow = True
                startInfo.WindowStyle = ProcessWindowStyle.Hidden

                Using print As System.Diagnostics.Process = Process.Start(startInfo)
                    'Chiude l'applicazione dopo x millisecondi con  WaitForExit(X)
                    '  print.WaitForExit(10000)
                    If print.HasExited = False Then
                        If print.CloseMainWindow() Then
                            printed = True
                        Else
                            printed = True
                        End If
                    Else
                        printed = True
                    End If
                    print.Close()
                End Using
            Else
                Throw New Exception("La Stampante NON è stata trovata nel sistema...")
            End If

        Catch ex As Exception
            Throw
        End Try
        Return printed
    End Function

    ''' <summary>
    ''' Ottieni le impostazioni predefinite della stampante nel sistema
    ''' </summary>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Public Shared Async Function GetDefaultPrinterSetting() As Task(Of PrinterSettings)

        Dim defaultPrinterSetting As PrinterSettings = Nothing

        For Each printer As String In PrinterSettings.InstalledPrinters

            defaultPrinterSetting = New System.Drawing.Printing.PrinterSettings
            defaultPrinterSetting.PrinterName = printer

            If defaultPrinterSetting.IsDefaultPrinter Then
                Return defaultPrinterSetting
            End If

        Next

        Return defaultPrinterSetting

    End Function

End Class
Posted
Updated 23-Mar-20 3:13am
Comments
EricERankin 5 days ago
   
You can refer to this Print PDF files in C# and VB.NET.
Note, you can find examples for Console, Windows Forms and WPF applications, they all use the same C# and VB.NET library for PDF.

1 solution

Rate this:
Please Sign up or sign in to vote.

Solution 1

defaultPrinterSetting.PrinterName = printer

defaultPrinterSetting.DefaultPageSettings.PaperSize.RawKind = System.Drawing.Printing.PaperKind.A4
   
Comments
Fabrizio Leoncini 4 days ago
   
Thanks a lot
Fabrizio

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)




CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100