asp.net vb web application printing data to a sticky label machine from web server - vb.net

I am developing a website where i'm pulling some data from a query and then needing to print this data to a brady pr300 plus label printer. I would like for the printing to happen automatically from the web server to the printer without having the print dialog box pop up on the client computer.
What is the best way to go about this? javascript, vb behind code?
I've been playing around with this without much luck. I created a printingclass with onbeginprint method and onprintpage method. When i call the print, it goes to the onbeginprint method, but for some reason it doesnt go to onprintpagemethod when i step through the code. The error i get is System.Drwaing.Printing.invalidprinterexception: no printers are installed.
I'm kind of stuck at the moment.
Public Sub PrintDocument()
Dim tprinter As New PCPrint
tprinter.PrinterFont = New Font("Verdana", 10)
tprinter.TextToPrint = "HELLO WORLD"
tprinter.PrintName = "testbrady"
tprinter.Print()
End Sub
Protected Overrides Sub OnBeginPrint(ByVal e As Printing.PrintEventArgs)
' Run base code
MyBase.OnBeginPrint(e)
'Check to see if the user provided a font
'if they didnt then we default to Times New Roman
If _font Is Nothing Then
'Create the font we need
_font = New Font("Times New Roman", 10)
End If
End Sub
Protected Overrides Sub OnPrintPage(ByVal e As Printing.PrintPageEventArgs)
' Run base code
MyBase.OnPrintPage(e)
'Declare local variables needed
Static curChar As Integer
Dim printHeight As Integer
Dim printWidth As Integer
Dim leftMargin As Integer
Dim rightMargin As Integer
Dim lines As Int32
Dim chars As Int32
'Set print area size and margins
With MyBase.DefaultPageSettings
printHeight = .PaperSize.Height - .Margins.Top - .Margins.Bottom
printWidth = .PaperSize.Width - .Margins.Left - .Margins.Right
leftMargin = .Margins.Left 'X
rightMargin = .Margins.Top 'Y
End With
MyBase.DefaultPageSettings.PrinterSettings.PrinterName = PrintName
'Check if the user selected to print in Landscape mode
'if they did then we need to swap height/width parameters
If MyBase.DefaultPageSettings.Landscape Then
Dim tmp As Integer
tmp = printHeight
printHeight = printWidth
printWidth = tmp
End If
'Now we need to determine the total number of lines
'we're going to be printing
Dim numLines As Int32 = CInt(printHeight / PrinterFont.Height)
'Create a rectangle printing are for our document
Dim printArea As New RectangleF(leftMargin, rightMargin, printWidth, printHeight)
'Use the StringFormat class for the text layout of our document
Dim format As New StringFormat(StringFormatFlags.LineLimit)
'Fit as many characters as we can into the print area
e.Graphics.MeasureString(_text.Substring(RemoveZeros(curChar)), PrinterFont, New SizeF(printWidth, printHeight), format, chars, lines)
'Print the page
e.Graphics.DrawString(_text.Substring(RemoveZeros(curChar)), PrinterFont, Brushes.Black, printArea, format)
'Increase current char count
curChar += chars
'Detemine if there is more text to print, if
'there is the tell the printer there is more coming
If curChar < _text.Length Then
e.HasMorePages = True
Else
e.HasMorePages = False
curChar = 0
End If
End Sub

Hello StackOverflow Members,
This is what i ended up doing to get the label printer to work.
Imports System.Drawing
Imports System.Drawing.Printing
Public Sub prt(variables)
Dim prn As New Printing.PrintDocument
Dim psz As New Printing.PaperSize With {
.RawKind = Printing.PaperKind.Custom,
.Width = 400,
.Height = 150
}
Using (prn)
prn.PrinterSettings.PrinterName = printer
prn.DefaultPageSettings.PaperSize = psz
prn.DefaultPageSettings.Margins.Left = 5
prn.DefaultPageSettings.Margins.Right = 5
prn.DefaultPageSettings.Margins.Top = 5
prn.DefaultPageSettings.Margins.Bottom = 5
AddHandler prn.PrintPage,
AddressOf Me.PrintPageHandler
prn.Print()
RemoveHandler prn.PrintPage,
AddressOf Me.PrintPageHandler
End Using
End Sub
Private Sub PrintPageHandler(ByVal sender As Object,
ByVal args As Printing.PrintPageEventArgs)
Dim shopnameX As Integer = 10, shopnameY As Integer = 10
Dim sfont As New Font("Arial Black", 14)
Dim strfomart As New StringFormat()
Dim StrRight As New StringFormat()
Dim StrLeft As New StringFormat()
strfomart.Alignment = StringAlignment.Center
StrRight.Alignment = StringAlignment.Far
StrLeft.Alignment = StringAlignment.Near
Dim dashValues As Single() = {5, 2, 5, 2}
Dim blackPen As New Pen(Color.Black, 1)
' blackPen.DashPattern = dashValues
Dim i As Integer, j As Integer
args.Graphics.DrawString(part.ToString, sfont, Brushes.Black, New
PointF(shopnameX, shopnameY))
End Sub

Related

Is there a way to use the graphics class methods (Graphics.DrawString or Graphics.DrawLine) for a PrintDocumet outside of the PrintPage event?

I'm rewriting a VB6 application in VB.net. Instead of using the VB6 printer namespace, I'm trying make the code natively VB.net compatible.
The VB6 application has a bunch of printer.print statements as well as a bunch of printer.line statements. (I believe the lines use TWIPs.) Here is an example of some of the lines.
Printer.DrawWidth = 1.5
Printer.Line (200, 12940)-(11275, 12940)
Printer.Line (200, 13680)-(6660, 13680)
Printer.Line (6712, 13680)-(11275, 13680)
Printer.FillStyle = vbFSTransparent
Printer.DrawWidth = 1
Printer.DrawStyle = vbDashDot
Printer.Circle (5700, 6000), draw_scale * BC_Diam / 2
media.FontItalic = True
Printer.Print "some text"
media.FontItalic = False
Printer.Print "additional, non italic text"
The only way I've been able to find how to do any of this in VB.net is by using the PrintDocument's PrintPage event. A problem with doing it this way is you have to pass all of the text to this subroutine all at once and deal with a "printArea" for word wrap. Another problem is it makes it very difficult to switch between italic and non italic text. In the same way for text, I think I would have to pass in all of the line/circle coordinates as well, then draw them from the event subroutine.
Private Sub document_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles document.PrintPage
Dim printFont As Font = New Font("Courier New", 8.5, FontStyle.Regular)
' Set print area size and margins
With document.DefaultPageSettings
Dim leftMargin As Integer = .Margins.Left 'X
Dim topMargin As Integer = .Margins.Top 'Y
Dim printHeight As Integer = .PaperSize.Height - topMargin * 2
Dim printWidth As Integer = .PaperSize.Width - leftMargin * 2
End With
' Check if the user selected to print in Landscape mode
' if they did then we need to swap height/width parameters
If document.DefaultPageSettings.Landscape Then
Dim tmp As Integer
tmp = printHeight
printHeight = printWidth
printWidth = tmp
End If
Dim lines As Int32
Dim chars As Int32
'Now we need to determine the total number of lines
'we're going to be printing
Dim numLines As Int32 = CInt(printHeight / printFont.Height)
' Create a rectangle printing are for our document
Dim printArea As New RectangleF(leftMargin, topMargin, printWidth, printHeight)
' Set format of string.
Dim format As New StringFormat(StringFormatFlags.LineLimit)
e.Graphics.MeasureString(txtText.Text.Substring(curChar), printFont, New SizeF(printWidth, printHeight), format, chars, lines)
e.Graphics.DrawString(txtText.Text.Substring(curChar), printFont, Brushes.Black, printArea, format)
'Increase current char count
curChar += chars
'Detemine if there is more text to print, if
'there is the tell the printer there is more coming
Debug.Print("curChar < txtText.Text.Length:" & (curChar < txtText.Text.Length))
If curChar < txtText.Text.Length Then
e.HasMorePages = True
Else
e.HasMorePages = False
curChar = 0
End If
End Sub
There has to be a better way to do this, right? How I can call Graphics.DrawLine, Graphics.DrawEllipse, Graphics.DrawString, etc. for the PrintDocument from outside of the PrintPage event in VB.net like you could in VB6?

Hasmorepages property fails

I have created a routine that is intended to print a variable number of lines and/or pages, based on a queue of line information previously stored. Each page prints fine, but when printing more than one page, two pages overprint. I can't see my logic error, but there must be one. A copy of the offending code is follows. Nextline.newpage is a boolean set to true to force a new page. In my text example there were six "Newpage" and "hasmorepages" was set to true six times, and the routine was exited six times. Still the output was four pages with one printing correctly, and three with two pages printed on one sheet. Any help would be greatly appreciated. By the way, this is my first question, so be kind.
Private Sub PrintLines(Sender As Object, e As PrintPageEventArgs) Handles PrintDoc.PrintPage
Dim White As String = GetARGBString(PrinterDefaultBackcolor)
Do Until Lines.Count = 0
Dim Nextline As Lineformat = Lines.Dequeue
If Nextline.NewPage Then
e.HasMorePages = True
Exit Sub
End If
With Nextline
Dim LineBackColor As String = Nextline.backColor
If LineBackColor <> White Or .Borders = True Then DrawShape(Nextline, e)
If .Text <> "" Then DrawText(Nextline, e)
End With
Loop
End Sub
Private Sub DrawShape(Line As Lineformat, E As PrintPageEventArgs)
With Line
Dim Top As Integer = .Top * 100
Dim Left As Integer = .Left * 100
Dim Width As Integer = .BackGroundWidth * 100
Dim Height As Integer = .BackGroundHeight * 100
Dim Point As New Point(Left, Top)
Dim Size As New Size(Width, Height)
Dim Rect As New Rectangle(Point, Size)
Dim TransparentFillColor As String = "00" & Strings.Right(.backColor, 6)
Dim FillColor As FullColor = GetColorFromString(.backColor)
Dim BorderPen As New Pen(Color.Black)
Dim FillBrush As New SolidBrush(FillColor.Color)
E.Graphics.FillRectangle(FillBrush, Rect)
If Line.Borders = True Then
E.Graphics.DrawRectangle(BorderPen, Rect)
End If
End With
End Sub
Private Sub DrawText(Line As Lineformat, E As PrintPageEventArgs)
With Line
Dim MyFont = SetFontStyle(.FontFamily, .FontPoints, .FontBold, .FontItalic, .FontUnderline)
Dim TextColor As FullColor = GetColorFromString(.ForeColor)
Dim MyBrush As New SolidBrush(TextColor.Color)
Dim top As Integer = .Top * 100
Dim Left As Integer = .Left * 100
Dim Width As Integer = .LineWidth * 100
Dim Height As Integer = .LineHeight * 100
Dim point As New Point(Left, top)
Dim Size As New Size(Width, Height)
Dim Rect As New RectangleF(point, Size)
Dim SF As New StringFormat()
SF.FormatFlags = TextFormatFlags.WordEllipsis
E.Graphics.DrawString(.Text, MyFont, MyBrush, Rect, SF)
End With
End Sub
End Class

Opening and closing multiple forms from a main form in VB.net

In my project (kind of a screen saver) I have a main form and second form (PicView).
I want to open many instances of the second form and display a picture in it.
I can do that fine, but when I have opened e.g. 4 forms I would like to close the first before opening the next one so that the total number of forms stays at 4.
The problem I have is that the closing routine does not know about the form instances and the debugger tells me to create a new instance, but I would like to use the existing ones.
How can I make the form names visible to the main routine or do I need to pass reference to the created forms?
Thanks
Private Sub btnTest_Click_1(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnTest.Click
gsPic1 = "D:\My Stuff\411CANON\IMG_1161.JPG"
gsPic2 = "D:\My Stuff\411CANON\IMG_1167.JPG"
gsPic3 = "D:\My Stuff\411CANON\IMG_1174.JPG"
gsPic4 = "D:\My Stuff\411CANON\IMG_1178.JPG"
ScreenSavePicIndex(gsPic1, 1)
Application.DoEvents()
ScreenSavePicIndex(gsPic2, 2)
Application.DoEvents()
ScreenSavePicIndex(gsPic3, 3)
Application.DoEvents()
ScreenSavePicIndex(gsPic4, 4)
MsgBox("Now Closing 1")
CloseScreenSaverPic(1)
Application.DoEvents()
MsgBox("Now Closing 3")
CloseScreenSaverPic(3)
Application.DoEvents()
MsgBox("Now Closing 4")
CloseScreenSaverPic(4)
Application.DoEvents()
End Sub
Private Sub CloseScreenSaverPic(ByVal iIndex As Integer)
Dim frmPicViewerScrSav(iIndex) As PicView
frmPicViewerScrSav(iIndex) = New PicView
frmPicViewerScrSav(iIndex).Close()
End Sub
Private Sub ScreenSavePicIndex(ByVal sFilePathandName As String, iIndex As Integer)
Dim iTargetHeight As Integer
Dim iTargetWidth As Integer
Dim dFactorHeight As Double
Dim dFactorWidth As Double
Dim objImage As System.Drawing.Image
Try
objImage = System.Drawing.Image.FromFile(sFilePathandName)
Catch ex As Exception
objImage = Nothing
End Try
Dim frmPicViewerScrSav(iIndex) As PicView
frmPicViewerScrSav(iIndex) = New PicView
Dim dFactor As Double
dFactor = 1
frmPicViewerScrSav(iIndex).FormBorderStyle = Windows.Forms.FormBorderStyle.None
iTargetWidth = Screen.PrimaryScreen.Bounds.Width / giScreenSavePicSize
iTargetHeight = Screen.PrimaryScreen.Bounds.Height / giScreenSavePicSize
'Check if the pic is bigger than what we want to display
If objImage.Width > iTargetWidth Then
'if it is wider then we need to find out how much bigger it is by factor
dFactorWidth = iTargetWidth / objImage.Width
End If
If objImage.Height > iTargetHeight Then
'if it is higher then we need to find out how much bigger it is by factor
dFactorHeight = iTargetHeight / objImage.Height
End If
If dFactorWidth > dFactorHeight Then
dFactor = dFactorWidth
Else
dFactor = dFactorHeight
End If
'Console.WriteLine("Factor is: " & dFactor)
frmPicViewerScrSav(iIndex).Width = objImage.Width * dFactor
frmPicViewerScrSav(iIndex).Height = objImage.Height * dFactor
objImage.Dispose()
Dim r As New Random()
Dim x As Integer = r.Next(Screen.PrimaryScreen.Bounds.Width - frmPicViewerScrSav(iIndex).Width)
Dim y As Integer = r.Next(Screen.PrimaryScreen.Bounds.Height - frmPicViewerScrSav(iIndex).Height)
Dim p As New Point(x, y)
'Console.WriteLine("Putting it at x= " & x & ", y= " & y)
frmPicViewerScrSav(iIndex).Location = p
frmPicViewerScrSav(iIndex).PictureBox1.Hide()
frmPicViewerScrSav(iIndex).PictureBox1.ImageLocation = sFilePathandName
frmPicViewerScrSav(iIndex).PictureBox1.SizeMode = PictureBoxSizeMode.Zoom
frmPicViewerScrSav(iIndex).PictureBox1.Show()
frmPicViewerScrSav(iIndex).Show()
End Sub

Using Encoding Parameters to merge TIFF Files

Edit: I found another example that creates the encoder params like this and I get the exact same error as befoer: "A generic error occurred in GDI+"
Dim info As ImageCodecInfo = Nothing
Dim ice As ImageCodecInfo
For Each ice In ImageCodecInfo.GetImageEncoders()
If ice.MimeType = "image/tiff" Then
info = ice
End If
Next ice 'use the save encoder
Dim enc As Encoder = Encoder.SaveFlag
Dim ep As New EncoderParameters(1)
ep.Param(0) = New EncoderParameter(enc, CLng(EncoderValue.MultiFrame))
ORIGINAL POST
VB.Net, Visual Studio 2012, .Net 4.5
I have been trying to write, borrow, or steal code that will merge multiple TIFF files in to a single tiff file. Every example, whether I write or get it from someplace fails on the same line with the exception, "A generic error occurred in GDI+". The line that causes the problem is DestinationImage.SaveAdd(img, imagePararms). There is just not enough to go on with that generic error message about a generic error. Has anyone experienced this?
Greg
Public Sub mergeTiffPages(str_DestinationPath As String, sourceFiles As String())
Dim codec As System.Drawing.Imaging.ImageCodecInfo = Nothing
For Each cCodec As System.Drawing.Imaging.ImageCodecInfo In System.Drawing.Imaging.ImageCodecInfo.GetImageEncoders()
If cCodec.CodecName = "Built-in TIFF Codec" Then
codec = cCodec
End If
Next
Try
Dim imagePararms As New System.Drawing.Imaging.EncoderParameters(1)
imagePararms.Param(0) = New System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, CLng(System.Drawing.Imaging.EncoderValue.MultiFrame))
If sourceFiles.Length = 1 Then
System.IO.File.Copy(DirectCast(sourceFiles(0), String), str_DestinationPath, True)
ElseIf sourceFiles.Length >= 1 Then
Dim DestinationImage As System.Drawing.Image = DirectCast(New System.Drawing.Bitmap(DirectCast(sourceFiles(0), String)), System.Drawing.Image)
DestinationImage.Save(str_DestinationPath, codec, imagePararms)
imagePararms.Param(0) = New System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, CLng(System.Drawing.Imaging.EncoderValue.FrameDimensionPage))
For i As Integer = 0 To sourceFiles.Length - 2
Dim img As System.Drawing.Image = DirectCast(New System.Drawing.Bitmap(DirectCast(sourceFiles(i), String)), System.Drawing.Image)
DestinationImage.SaveAdd(img, imagePararms)
img.Dispose()
Next
imagePararms.Param(0) = New System.Drawing.Imaging.EncoderParameter(System.Drawing.Imaging.Encoder.SaveFlag, CLng(System.Drawing.Imaging.EncoderValue.Flush))
DestinationImage.SaveAdd(imagePararms)
imagePararms.Dispose()
DestinationImage.Dispose()
End If
Catch ex As Exception
MsgBox(ex.Message)
End Try
End Sub
Although I did not find a solution for this code I did find code that works. JohnH a moderator at http://www.vbdotnetforums.com/ posted the code below in this thread http://www.vbdotnetforums.com/graphics-gdi/22113-create-multipage-tiff-loop.html
It works for me. I added a few lines at the top to show how I called it.
Greg
'Example: Combine 4 tiff images in a new file called FinishedTiff.tiff
'Dim oNewImage As Image
'oNewImage = Image.FromFile("C:\IRISScan\Week of Jan 6 no SSN_Page_1.tif")
'SaveAddTiff(oNewImage, "C:\IRISScan\FinishedTiff.tif")
'oNewImage = Image.FromFile("C:\IRISScan\Week of Jan 6 no SSN_Page_2.tif")
'SaveAddTiff(oNewImage, "C:\IRISScan\FinishedTiff.tif")
'oNewImage = Image.FromFile("C:\IRISScan\Document3_Page_1.tif")
'SaveAddTiff(oNewImage, "C:\IRISScan\FinishedTiff.tif")
'oNewImage = Image.FromFile("C:\IRISScan\Document3_Page_2.tif")
'SaveAddTiff(oNewImage, "C:\IRISScan\FinishedTiff.tif")
Imports System.Drawing.Imaging
Module modTiff
'
Sub SaveAddTiff(ByVal img As Image, ByVal filename As String)
If Not IO.File.Exists(filename) Then
img.Save(filename, Imaging.ImageFormat.Tiff)
Else
Dim frames As List(Of Image) = getFrames(filename)
frames.Add(img)
SaveMultiTiff(frames.ToArray, filename)
End If
img.Dispose()
End Sub
Sub SaveMultiTiff(ByVal frames() As Image, ByVal filename As String)
Dim codec As ImageCodecInfo = getTiffCodec()
Dim enc As Encoder = Encoder.SaveFlag
Dim ep As New EncoderParameters(2)
ep.Param(0) = New EncoderParameter(enc, CLng(EncoderValue.MultiFrame))
ep.Param(1) = New EncoderParameter(Encoder.Compression, CLng(EncoderValue.CompressionNone))
Dim tiff As Image = frames(0)
tiff.Save(filename, codec, ep)
ep.Param(0) = New EncoderParameter(enc, CLng(EncoderValue.FrameDimensionPage))
For i As Integer = 1 To frames.Length - 1
tiff.SaveAdd(frames(i), ep)
frames(i).Dispose()
Next
ep.Param(0) = New EncoderParameter(enc, CLng(EncoderValue.Flush))
tiff.SaveAdd(ep)
tiff.Dispose()
End Sub
Function getTiffCodec() As ImageCodecInfo
For Each ice As ImageCodecInfo In ImageCodecInfo.GetImageEncoders()
If ice.MimeType = "image/tiff" Then
Return ice
End If
Next
Return Nothing
End Function
Function getFrames(ByVal filename) As List(Of Image)
Dim frames As New List(Of Image)
Dim img As Image = Image.FromFile(filename)
For i As Integer = 0 To img.GetFrameCount(Imaging.FrameDimension.Page) - 1
img.SelectActiveFrame(Imaging.FrameDimension.Page, i)
Dim tmp As New Bitmap(img.Width, img.Height)
Dim g As Graphics = Graphics.FromImage(tmp)
g.CompositingQuality = Drawing2D.CompositingQuality.HighQuality
g.InterpolationMode = Drawing2D.InterpolationMode.HighQualityBicubic
g.PixelOffsetMode = Drawing2D.PixelOffsetMode.HighQuality
g.SmoothingMode = Drawing2D.SmoothingMode.HighQuality
g.TextRenderingHint = Drawing.Text.TextRenderingHint.AntiAliasGridFit
g.DrawImageUnscaled(img, 0, 0)
frames.Add(tmp)
g.Dispose()
Next
img.Dispose()
Return frames
End Function
End Module
I replaced
g.DrawImageUnscaled(img, 0, 0)
with
g.DrawImageUnscaledAndClipped(img, New Rectangle(0, 0, img.Width, img.Height))
and it fixed the scaling issue where it would shrink the image to a quarter of its original size

Live text reader with highlighting in VB.net

I have a program which writes to a .log file as it is installing software.
Some of the lines will contain either WARNING or FAILED.
What I would like, is a window in my program which will read the .log file and display the content into this window as it is being written too. Any lines which contain WARNING or FAILED in them are highlighted yellow/red.
Does anyone know how to do this?
Create a FORM (I used VB 2010) and add this code.
it will write 3 lines on the form in 2 colours.
It might get you on your way. Ask MSDN help for each function that is new to you.
Private Sub Form1_Paint(sender As Object, e As System.Windows.Forms.PaintEventArgs) Handles Me.Paint
Dim chRs(0) As CharacterRange
Dim sbRs(0) As SolidBrush
Dim flRs(0) As SolidBrush
Dim blueBrush As New SolidBrush(Color.Blue)
Dim whiteBrush As New SolidBrush(Color.White)
Dim redBrush As New SolidBrush(Color.Red)
Dim EditFont As New Font("Courier New", 9)
Dim stringFormat As New StringFormat
Dim aRectangle As Rectangle
Dim RectHeight As Integer = 20
For i = 1 To 3
Dim txt As String = "a string " & CStr(i)
If i = 2 Then
sbRs(0) = blueBrush
Else
sbRs(0) = redBrush
End If
flRs(0) = whiteBrush
chRs(0) = New CharacterRange(0, txt.Length())
Dim chRsa As Array = Array.CreateInstance(GetType(CharacterRange), 1)
Array.Copy(chRs, 0, chRsa, 0, 1)
aRectangle = New Rectangle(0, CInt((i - 1) * RectHeight), ClientRectangle.Size.Width, RectHeight) ' x, y, w, h
stringFormat.SetMeasurableCharacterRanges(chRsa)
Dim stringRegions As Array = Array.CreateInstance(GetType([Region]), 1)
stringRegions = e.Graphics.MeasureCharacterRanges(txt, EditFont, aRectangle, stringFormat)
Dim measureRect1 As RectangleF = stringRegions(0).GetBounds(e.Graphics)
Dim g As Graphics = e.Graphics
g.FillRectangle(flRs(0), measureRect1)
g.DrawString(txt.Substring(chRs(0).First, chRs(0).Length), EditFont, sbRs(0), CSng(measureRect1.X), CSng(measureRect1.Y))
Next
End Sub