[Okta Webinar] Learn how to a build a cloud-first strategyRegister Now

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 704
  • Last Modified:

Printing the contents of a TextBox

Hi, I'm using VB.NET2010, WinForms. I have a Form with a textbox, where I append some text to the textbox after parsing an external text file. That part works well.

I allow my users to scroll through the textbox and view the output, but I'd also like to allow them to print the context of the textbox.

How can I accomplish that?

Thanks,
Fulano
0
Mr_Fulano
Asked:
Mr_Fulano
  • 5
  • 4
  • 3
  • +1
2 Solutions
 
käµfm³d 👽Commented:
I gave an example here:  http://www.experts-exchange.com/Programming/Languages/.NET/Visual_Basic.NET/Q_26901714.html . It prints a ListBox, but you could modify it to print the TextBox's text.
0
 
Mr_FulanoAuthor Commented:
Hi Kaufmed, your solution almost works...It prints the first line vertically and nothing else. I think the problem is that you were using a listbox and I'm using a Textbox. I'll have to look into it further. I would also like a Print Preview of what is going to be printed rather than launching it to the printer blindly.

Fulano
0
Independent Software Vendors: We Want Your Opinion

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
Mr_FulanoAuthor Commented:
Hi Mike, I'll look you suggestion over, but it rather long. May take me a while.

Thanks,
Fulano
0
 
käµfm³d 👽Commented:
Hi Kaufmed, your solution almost works...It prints the first line vertically and nothing else.
I did say you'd need to modify it to fit a TextBox. I have modified the previous example below, but you'll need to further expand upon it to calculate line breaks because as is, the code will print a line even if it extends past the page (i.e. you will lose the latter part of your strings). You could either scale the font down (not the best choice), or use MeasureString() to determine how long a string. You would compare the returned SizeF object's Width property to the width of your page.

As far as a print preview you can use the PrintPreviewDialog, but the downside is that it only prints to the default printer--there is no option to select a different printer. You would use this dialog in conjunction with PrintDocument. The code I had in the previous example can be copy/pasted into the handler for the PrintPage event of the PrintDocument class. Again, you would need to modify the code to insert line breaks appropriately.
Public Class Form1

    Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
        Me.PrintPreviewDialog1.Document = Me.PrintDocument1
        Me.PrintPreviewDialog1.ShowDialog()
    End Sub

    Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        Dim f As New Font("Arial", 10)
        Dim vOffset As SizeF

        For Each item As String In Me.TextBox1.Lines
            vOffset += e.Graphics.MeasureString(item, f, 300)   ' Get the height of the string as it would be on the page; accumulate so text doesn't overlap
            e.Graphics.DrawString(item, f, Brushes.Black, 0, vOffset.Height + 5)    ' Draw the string on the page
        Next
    End Sub

End Class

Open in new window

0
 
Carlos VillegasFull Stack .NET DeveloperCommented:
kaufmed solution will work if it implement the StringFormat class to wrap the text to the printable area...
0
 
Carlos VillegasFull Stack .NET DeveloperCommented:
It is a parameter of e.Graphics.DrawString(.....), the printable area is required too, maybe e.PageBounds
0
 
käµfm³d 👽Commented:
An example:
Untitled.png
0
 
Mr_FulanoAuthor Commented:
I"m working through kaufmed new solution. It prints the first page (albeit with too many spaces between the lines), but it stops at page 1. I'm going to try and make it print the other pages as well.

I am SOOOOOO disgusted with Microsoft that they've sold Visual Studio for so many years and have not addressed the problems with the printing features. This absolutely is the worst for printing that I've every seen.

Fulano

 
0
 
Mr_FulanoAuthor Commented:
OK, here is the end result...Its a combination of some of kaufmed's suggestions with the PrintPreview option and the suggestions made by Miketonny. I cobbled them both together to get what I needed. Thanks to you both.

Fulano
Dim StringToPrint As String

    Private Sub btnPrint_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnPrint.Click
        StringToPrint = tbxOutPut.Text
        Me.PrintPreviewDialog1.Document = Me.PrintDocument1
        Me.PrintPreviewDialog1.ShowDialog()
    End Sub

    Private Sub PrintDocument1_PrintPage(ByVal sender As System.Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        Dim numChars As Integer
        Dim numLines As Integer
        Dim stringForPage As String
        Dim strFormat As New StringFormat()
        Dim PrintFont As New Font("Courier", 7)

        PrintFont = tbxOutPut.Font

        Dim rectDraw As New RectangleF(e.MarginBounds.Left, e.MarginBounds.Top, e.MarginBounds.Width, e.MarginBounds.Height)
        Dim sizeMeasure As New SizeF(e.MarginBounds.Width, e.MarginBounds.Height - PrintFont.GetHeight(e.Graphics))

        strFormat.Trimming = StringTrimming.Word

        e.Graphics.MeasureString(StringToPrint, PrintFont, sizeMeasure, strFormat, numChars, numLines)


        stringForPage = StringToPrint.Substring(0, numChars)

        e.Graphics.DrawString(stringForPage, PrintFont, Brushes.Black, rectDraw)

        If numChars < StringToPrint.Length Then

            StringToPrint = StringToPrint.Substring(numChars)

            e.HasMorePages = True

        Else

            e.HasMorePages = False

        End If
    End Sub

Open in new window

0
 
Mr_FulanoAuthor Commented:
Good suggestions. - Thanks!
0
 
Carlos VillegasFull Stack .NET DeveloperCommented:
Hello Fulano, I know that it is a closed question but I want to share this, if your print requirements are very basic maybe this can help you too:
    Sub SimpleTextPrint(ByVal text As String, Optional ByVal toDefaultPrinter As Boolean = True)
        Dim myTempFilePath As String = Nothing
        Try
            myTempFilePath = System.IO.Path.GetTempFileName()
            System.IO.File.WriteAllText(myTempFilePath, text)
            Using notepad As New System.Diagnostics.Process()
                notepad.StartInfo = New System.Diagnostics.ProcessStartInfo("notepad", IIf(toDefaultPrinter, "/P ", "") & """" & myTempFilePath & """")
                notepad.StartInfo.WindowStyle = IIf(toDefaultPrinter, ProcessWindowStyle.Hidden, ProcessWindowStyle.Maximized)
                notepad.Start()
                notepad.WaitForExit()
            End Using
        Catch ex As Exception
        Finally
            If Not String.IsNullOrEmpty(myTempFilePath) Then
                System.IO.File.Delete(myTempFilePath)
            End If
        End Try
    End Sub

Open in new window

I still preferring the custom .NET printing, but I just want to share this approach too.
Have a nice day.
0
 
Carlos VillegasFull Stack .NET DeveloperCommented:
:p I forgot to do some err handling code
0

Featured Post

Free Tool: Path Explorer

An intuitive utility to help find the CSS path to UI elements on a webpage. These paths are used frequently in a variety of front-end development and QA automation tasks.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 5
  • 4
  • 3
  • +1
Tackle projects and never again get stuck behind a technical roadblock.
Join Now