Condividi tramite


Stampa utilizzando l'anteprima di stampa

Nella programmazione Windows Form è comune offrire l'anteprima di stampa oltre ai servizi di stampa. Un modo semplice per aggiungere l'anteprima di stampa all'applicazione consiste nell'usare un PrintPreviewDialog controllo in combinazione con PrintPage la logica di gestione degli eventi per la stampa di un file.

Per visualizzare in anteprima un documento di testo con un controllo PrintPreviewDialog

  1. In Visual Studio, usare il riquadro Esplora soluzioni e fare doppio clic sul modulo da cui si desidera stampare. Questo apre il Visual Designer.

  2. Nel riquadro casella degli strumenti fare doppio clic sul componente e sul componente per aggiungerli al modulo.

  3. Aggiungere un Button al modulo oppure usare un pulsante già presente nel modulo.

  4. Nella finestra di progettazione visiva del modulo selezionare il pulsante . Nel riquadro Proprietà, selezionare il pulsante di filtro Evento e quindi fare doppio clic sull'evento Click per generare un gestore eventi.

  5. Il codice evento Click deve essere visibile. All'esterno dell'ambito del gestore eventi, aggiungere due variabili stringa private alla classe denominata documentContents e stringToPrint:

    // Declare a string to hold the entire document contents.
    private string documentContents="";
    
    // Declare a variable to hold the portion of the document that
    // is not printed.
    private string stringToPrint="";
    
    ' Declare a string to hold the entire document contents.
    Private documentContents As String
    ' Declare a variable to hold the portion of the document that
    ' is not printed.
    Private stringToPrint As String
    
  6. Tornare al codice del gestore eventi Click, impostare la proprietà DocumentName sul documento da stampare e aprire e leggere il contenuto del documento sulla stringa aggiunta in precedenza.

    string docName = "testPage.txt";
    string docPath = @"C:\";
    string fullPath = System.IO.Path.Combine(docPath, docName);
    printDocument1.DocumentName = docName;
    stringToPrint = System.IO.File.ReadAllText(fullPath);
    
    Dim docName As String = "testPage.txt"
    Dim docPath As String = "C:\Users\v-rsatao\Desktop\"
    Dim fullPath As String = System.IO.Path.Combine(docPath, docName)
    
    PrintDocument1.DocumentName = docName
    stringToPrint = System.IO.File.ReadAllText(fullPath)
    
  7. Come si farebbe per stampare il documento, nel gestore eventi PrintPage utilizzare la proprietà Graphics della classe PrintPageEventArgs e il contenuto del file per calcolare le righe per pagina ed eseguire il rendering del contenuto del documento. Dopo aver disegnato ogni pagina, verificare se si tratta dell'ultima pagina e impostare di conseguenza la proprietà HasMorePages del PrintPageEventArgs. L'evento PrintPage viene generato fino a quando HasMorePages è false. Al termine del rendering del documento, reimpostare la stringa da renderizzare. Assicurarsi inoltre che l'evento PrintPage sia associato al metodo di gestione degli eventi.

    Annotazioni

    Se è stata implementata la stampa nell'applicazione, i passaggi 5 e 6 potrebbero essere già stati completati.

    Nell'esempio di codice seguente il gestore eventi viene usato per stampare il file "testPage.txt" nello stesso tipo di carattere utilizzato nel modulo.

    void PrintDocument1_PrintPage(object sender, PrintPageEventArgs e)
    {
        int charactersOnPage = 0;
        int linesPerPage = 0;
    
        // Sets the value of charactersOnPage to the number of characters
        // of stringToPrint that will fit within the bounds of the page.
        e.Graphics.MeasureString(stringToPrint, this.Font,
            e.MarginBounds.Size, StringFormat.GenericTypographic,
            out charactersOnPage, out linesPerPage);
    
        // Draws the string within the bounds of the page.
        e.Graphics.DrawString(stringToPrint, this.Font, Brushes.Black,
        e.MarginBounds, StringFormat.GenericTypographic);
    
        // Remove the portion of the string that has been printed.
        stringToPrint = stringToPrint.Substring(charactersOnPage);
    
        // Check to see if more pages are to be printed.
        e.HasMorePages = (stringToPrint.Length > 0);
    
        // If there are no more pages, reset the string to be printed.
        if (!e.HasMorePages)
            stringToPrint = documentContents;
    }
    
    Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs) Handles PrintDocument1.PrintPage
    
        Dim charactersOnPage As Integer = 0
        Dim linesPerPage As Integer = 0
    
        ' Sets the value of charactersOnPage to the number of characters 
        ' of stringToPrint that will fit within the bounds of the page.
        e.Graphics.MeasureString(stringToPrint, Me.Font, e.MarginBounds.Size,
            StringFormat.GenericTypographic, charactersOnPage, linesPerPage)
    
        ' Draws the string within the bounds of the page.
        e.Graphics.DrawString(stringToPrint, Me.Font, Brushes.Black,
            e.MarginBounds, StringFormat.GenericTypographic)
    
        ' Remove the portion of the string that has been printed.
        stringToPrint = StringToPrint.Substring(charactersOnPage)
    
        ' Check to see if more pages are to be printed.
        e.HasMorePages = stringToPrint.Length > 0
    
        ' If there are no more pages, reset the string to be printed.
        If Not e.HasMorePages Then
            stringToPrint = documentContents
        End If
    
    End Sub
    
  8. Impostare la proprietà Document del controllo PrintPreviewDialog sul componente PrintDocument nel form.

    printPreviewDialog1.Document = printDocument1;
    
    PrintPreviewDialog1.Document = PrintDocument1
    
  9. Chiamare il metodo ShowDialog nel controllo PrintPreviewDialog. Si noti il seguente codice evidenziato: in genere si chiama ShowDialog dal metodo di gestione dell'evento di un pulsante Click. Chiamando ShowDialog genera l'evento PrintPage e visualizza l'output sul controllo PrintPreviewDialog. Quando l'utente seleziona l'icona di stampa nella finestra di dialogo, l'evento PrintPage viene generato nuovamente, inviando l'output alla stampante anziché alla finestra di dialogo di anteprima. Di conseguenza, la stringa viene reimpostata alla fine del processo di rendering nel passaggio 4.

    Nell'esempio di codice seguente viene illustrato il metodo di gestione degli eventi Click per un pulsante nel modulo. Il metodo di gestione degli eventi chiama i metodi per leggere il documento e visualizzare la finestra di dialogo anteprima di stampa.

    private void Button1_Click(object sender, EventArgs e)
    {
        string docName = "testPage.txt";
        string docPath = @"C:\";
        string fullPath = System.IO.Path.Combine(docPath, docName);
        printDocument1.DocumentName = docName;
        stringToPrint = System.IO.File.ReadAllText(fullPath);
    
        printPreviewDialog1.Document = printDocument1;
    
        printPreviewDialog1.ShowDialog();
    }
    
    Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
    
        Dim docName As String = "testPage.txt"
        Dim docPath As String = "C:\Users\v-rsatao\Desktop\"
        Dim fullPath As String = System.IO.Path.Combine(docPath, docName)
    
        PrintDocument1.DocumentName = docName
        stringToPrint = System.IO.File.ReadAllText(fullPath)
    
        PrintPreviewDialog1.Document = PrintDocument1
    
        PrintPreviewDialog1.ShowDialog()
    
    End Sub
    

Vedere anche