2013-04-03 34 views
6
Private Sub btnPreview_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPreview.Click 
    preview.PrintPreviewControl.Zoom = 1 
    preview.Document = print 
    print.PrinterSettings.DefaultPageSettings.Landscape = True 
    preview.Show() 

    AddHandler print.PrintPage, AddressOf print_PrintPage 

End Sub 

Protected Sub print_PrintPage(ByVal sender As Object, ByVal e As PrintPageEventArgs) 
    Dim ColumnCount As Integer = DataGridView1.ColumnCount 
    Dim RowCount As Integer = DataGridView1.RowCount 

    Dim CellTopPos As Integer = print.PrinterSettings.DefaultPageSettings.Margins.Top 

    For Row = 0 To RowCount - 1 

     Dim CellLeftPos As Integer = print.PrinterSettings.DefaultPageSettings.Margins.Left 

     For Cell = 0 To ColumnCount - 1 

      Dim CellValue As String = DataGridView1.Rows(Row).Cells(Cell).Value.ToString() 
      Dim CellWidth = DataGridView1.Rows(Row).Cells(Cell).Size.Width + 50 
      Dim CellHeight = DataGridView1.Rows(Row).Cells(Cell).Size.Height 

      Dim Brush As New SolidBrush(Color.Black) 
      e.Graphics.DrawString(CellValue, New Font("Century Gothic", 10), Brush, CellLeftPos, CellTopPos) 
      e.Graphics.DrawRectangle(Pens.Black, CellLeftPos, CellTopPos, CellWidth, CellHeight) 

      CellLeftPos += CellWidth 
     Next 

     CellTopPos += DataGridView1.Rows(Row).Cells(0).Size.Height 
    Next 

End Sub 

這是用於預覽和打印我的datagridview內容的代碼。我嘗試使用DefaultPageSettings代碼,但它不起作用。林還試圖將其打印在中心的格式以橫向格式打印和預覽DataGridView

回答

6

嘗試設置的PrintDocument的DefaultPageSettings屬性,而不是PrinterSettings:

'PrintDocument1.PrinterSettings.DefaultPageSettings.Landscape = True 
PrintDocument1.DefaultPageSettings.Landscape = True 
+0

我怎麼能中心的內容,我的打印預覽? –

0

可以使用這樣的代碼

Dim preview As PrintPreviewDialog 
    Dim PageSetup As PageSetupDialog 
    PageSetup = New PageSetupDialog 
    preview = New PrintPreviewDialog 
    PageSetup.PageSettings = PrintDocument1.DefaultPageSettings 
    PageSetup.ShowDialog() 
    preview.PrintPreviewControl.Zoom = 1 
    preview.Document = PrintDocument1 

    preview.ShowDialog()