Archive for category vb.net

Encryption and Decryption of strings with C#

Well I am checking out the Beale Street Historic District for the first time in Memphis, TN tonight. I have heard a lot about it since my arrival here so am excited to get to go. I think it will be fun.

Of course this would come up. I had written this previously in vb.net and I had the opportunity to use it again today. Of course in doing so, I discovered a bad coding practice violation I had committed. I had failed to return a value in my function’s Catch block of my code. C# doesn’t let you off the hook so easily and will bug you till you fix it. As noted previously, topic is encryption and decryption of strings. It is straightforward but you might find it useful. Simply pass in the string you want to encrypt/decrypt and the key you want to use.

using System;
using System.IO;
using System.Text;
using System.Security.Cryptography;
public class Crypto
{
    private static TripleDESCryptoServiceProvider DES = new TripleDESCryptoServiceProvider();
    private static MD5CryptoServiceProvider MD5 = new MD5CryptoServiceProvider();
    public static byte[] MD5Hash(string value)
    {
        return MD5.ComputeHash(ASCIIEncoding.ASCII.GetBytes(value));
    }
    public static string Encrypt(string stringToEncrypt, string key)
    {
        DES.Key = Crypto.MD5Hash(key);
        DES.Mode = CipherMode.ECB;
        byte[] Buffer = ASCIIEncoding.ASCII.GetBytes(stringToEncrypt);
        return Convert.ToBase64String(DES.CreateEncryptor().TransformFinalBlock(Buffer, 0, Buffer.Length));
    }
    public static string Decrypt(string encryptedString, string key)
    {
        try
        {
            DES.Key = Crypto.MD5Hash(key);
            DES.Mode = CipherMode.ECB;
            byte[] Buffer = Convert.FromBase64String(encryptedString);
            return ASCIIEncoding.ASCII.GetString(DES.CreateDecryptor().TransformFinalBlock(Buffer, 0, Buffer.Length));
        }
        catch (Exception ex)
        {
            MessageBox.Show(“Invalid Key”, “Decryption Failed”, MessageBoxButtons.OK, MessageBoxIcon.Exclamation);
        }
// Inserted the following ‘return’ since all code paths must return a value in C#:
        return null;
    }
}

And now it’s usage…..

public class Form1
{
    private void Button1_Click(object sender, System.EventArgs e)
    {
        string key = Microsoft.VisualBasic.Interaction.InputBox(“Enter a Key:”, “”, “”, -1, -1);
        Label1.Text = Crypto.Encrypt(TextBox1.Text, key);
        TextBox1.Clear();
    }
    private void Button2_Click(object sender, System.EventArgs e)
    {
        string key = Microsoft.VisualBasic.Interaction.InputBox(“Enter a Key:”, “”, “”, -1, -1);
        TextBox1.Text = Crypto.Decrypt(Label1.Text, key);
    }

    }


Join me on Facebook

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

3 Comments

Save Control Settings with vb.net

What’s this you say? A new blog entry? If you haven’t completely deserted me …. well I don’t know what’s wrong with you! Smile jk. But anyway here is the latest. I am working for a national hotel chain in Memphis, TN. I got married, moved to New Jersey and am we are now separated. Yes it is a long story and no I am not going to bore you with the details!

Before I go any further, I actually write very little in vb.net anymore. The language is awesome. It’s just that very few people want that skill set now and if you want to be employed you need to write in C#. It’s just the way it is. However in this particular task, I found vb.net to be the tool of choice here. The reason is there is no C# equivalent to VB’s implicit ‘once only’ variable initialization within loops. I am not sure why that is but that is the case here. This code snippet is ideal when you want to allow the end user to dictate how a given control is to look or operate. Yes in my example I am using an Infragistic control so if you copy and paste this do NOT email me complaining about broken references please! I hope you find the code useful and thank you for showing up! Smile

Public Shared Sub SaveControl(ByVal StateName As String, ByVal ParamArray Controls As Control())
        Dim section As String = “”
        Dim appName As String = StringType.FromObject(Interaction.IIf((StringType.StrCmp(Application.ProductName, “”, False) = 0), “VSDesigner”, Application.ProductName))
        Dim control As Control
        For Each control In Controls
            If (Not control.FindForm Is Nothing) Then
                Dim form As Form
                If (StringType.StrCmp((StateName & “”), “”, False) > 0) Then
                    section = String.Concat(New String() { control.FindForm.Name, “.”, control.Name, “.”, StateName })
                Else
                    section = (control.FindForm.Name & “.” & control.Name)
                End If
                If TypeOf control Is Form Then
                    form = DirectCast(control, Form)
                    If (form.WindowState = FormWindowState.Normal) Then
                        Interaction.SaveSetting(appName, form.Name, “Top”, StringType.FromInteger(form.Top))
                        Interaction.SaveSetting(appName, form.Name, “Left”, StringType.FromInteger(form.Left))
                        Interaction.SaveSetting(appName, form.Name, “Height”, StringType.FromInteger(form.Height))
                        Interaction.SaveSetting(appName, form.Name, “Width”, StringType.FromInteger(form.Width))
                    End If
                    Interaction.SaveSetting(appName, form.Name, “WindowState”, StringType.FromInteger(CInt(form.WindowState)))
                ElseIf TypeOf control Is Splitter Then
                    form = control.FindForm
                    Dim splitter As Splitter = DirectCast(control, Splitter)
                    Interaction.SaveSetting(appName, section, “SplitPosition”, StringType.FromInteger(splitter.SplitPosition))
                ElseIf TypeOf control Is FilterListView Then
                    Dim view2 As FilterListView = DirectCast(control, FilterListView)
                    form = view2.FindForm
                    Interaction.SaveSetting(appName, section, “View”, StringType.FromInteger(CInt(view2.ListView.View)))
                    Dim header As ColumnHeader
                    For Each header In view2.ListView.Columns
                        Interaction.SaveSetting(appName, section, (“Column” & StringType.FromInteger(header.Index)), StringType.FromInteger(header.Width))
                    Next
                    Dim filter As FilterListViewFilter
                    For Each filter In view2.Filters
                        Dim tag As UserProfileSetting
                        If (filter.Tag Is Nothing) Then
                            tag = Context.User.Settings.NewItem
                            Dim setting2 As UserProfileSetting = tag
                            setting2.Type = UserProfileSettingTypeEnum.FilterListView
                            setting2.Name = section
                            setting2.Description = filter.Name
                            setting2.Value = filter.Filter
                            setting2 = Nothing
                            filter.Tag = tag
                        ElseIf filter.Deleted Then
                            tag = DirectCast(filter.Tag, UserProfileSetting)
                            If Context.User.Settings.Contains(tag) Then
                                Context.User.Settings.Remove(tag)
                            End If
                        Else
                            tag = DirectCast(filter.Tag, UserProfileSetting)
                            tag.Value = filter.Filter
                        End If
                    Next
                    Context.User.Settings.Save
                ElseIf (TypeOf control Is ListView Or TypeOf control Is SortListView) Then
                    form = control.FindForm
                    Dim view As ListView = DirectCast(control, ListView)
                    Interaction.SaveSetting(appName, section, “View”, StringType.FromInteger(CInt(view.View)))
                    Dim header As ColumnHeader
                    For Each header In view.Columns
                        Interaction.SaveSetting(appName, section, (“Column” & StringType.FromInteger(header.Index)), StringType.FromInteger(header.Width))
                    Next
                ElseIf TypeOf control Is TabControl Then
                    form = control.FindForm
                    Dim control2 As TabControl = DirectCast(control, TabControl)
                    Interaction.SaveSetting(appName, section, “View”, StringType.FromInteger(control2.SelectedIndex))
                ElseIf TypeOf control Is TextBox Then
                    form = control.FindForm
                    Dim box3 As TextBox = DirectCast(control, TextBox)
                    Interaction.SaveSetting(appName, section, “Text”, box3.Text)
                ElseIf TypeOf control Is ComboBox Then
                    form = control.FindForm
                    Dim box As ComboBox = DirectCast(control, ComboBox)
                    If (box.DropDownStyle = ComboBoxStyle.DropDown) Then
                        Interaction.SaveSetting(appName, section, “Text”, box.Text)
                    End If
                    Interaction.SaveSetting(appName, section, “SelectedIndex”, StringType.FromInteger(box.SelectedIndex))
                ElseIf TypeOf control Is CheckBox Then
                    form = control.FindForm
                    Dim box2 As CheckBox = DirectCast(control, CheckBox)
                    Interaction.SaveSetting(appName, section, “Checked”, StringType.FromBoolean(box2.Checked))
                ElseIf TypeOf control Is DataGrid Then
                    form = control.FindForm
                    Dim grid As DataGrid = DirectCast(control, DataGrid)
                    Dim num As Integer = 0
                    Dim style As DataGridTableStyle
                    For Each style In grid.TableStyles
                        Dim num2 As Integer = 0
                        Dim style2 As DataGridColumnStyle
                        For Each style2 In style.GridColumnStyles
                            Interaction.SaveSetting(appName, (section & StringType.FromInteger(num) & “.” & StringType.FromInteger(num2)), “Width”, StringType.FromInteger(style2.Width))
                            num2 += 1
                        Next
                        num += 1
                    Next
                ElseIf TypeOf control Is KeyedDropDown Then
                    form = control.FindForm
                    Dim down As KeyedDropDown = DirectCast(control, KeyedDropDown)
                    If (down.DropDownStyle = ComboBoxStyle.DropDown) Then
                        Interaction.SaveSetting(appName, section, “Text”, down.Text)
                    End If
                    Interaction.SaveSetting(appName, section, “SelectedIndex”, StringType.FromInteger(down.SelectedIndex))
                ElseIf TypeOf control Is UltraGrid Then
                    Dim grid2 As UltraGrid = DirectCast(control, UltraGrid)
                    Dim enumerator2 As BandEnumerator = grid2.DisplayLayout.Bands.GetEnumerator
                    Do While enumerator2.MoveNext
                        Dim current As UltraGridBand = enumerator2.Current
                        Dim enumerator As ColumnEnumerator = current.Columns.GetEnumerator
                        Do While enumerator.MoveNext
                            Dim column As UltraGridColumn = enumerator.Current
                            Interaction.SaveSetting(appName, section, (“Hidden.” & StringType.FromInteger(current.Index) & “.” & column.Key), StringType.FromBoolean(column.Hidden))
                            Interaction.SaveSetting(appName, section, (“Width.” & StringType.FromInteger(current.Index) & “.” & column.Key), StringType.FromInteger(column.Width))
                        Loop
                    Loop
                End If
            End If
        Next
    End Sub

Facebook

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

Leave a comment

Convert Visio Pages to Images in vb.net

I have been fooling around with Visio automation since attempting to help a friend with a project that did so. In the course of this I did this code snippet to convert the Visio page to an image. The code loops through and takes each page and converts it to an image. Pretty basic. I have not posted in a while and my apologies to those of you who were wondering…. Smile

Here is the code….

Sub SaveAsImage()
‘ creates an invisible Visio instance, opens a document, then
‘ saves all pages in the document as jpg images using
‘ page name and page number as file name
 
    Dim vsoApp As Visio.Application
    Dim vsoDoc As Visio.Document
    Dim PathName As String, jpgName As String
    Dim pg As Visio.Page
  
    Set vsoApp = CreateObject(“Visio.InvisibleApp”)
    ‘ SET PATH/FILENAME BELOW TO VSD ON YOUR SYSTEM
    Set vsoDoc = vsoApp.Documents.Open(“c:\TEST\test.vsd”)
  
    PathName = vsoApp.Documents(1).Path      ‘ Set pathname to that of first document
           
    For Each pg In vsoApp.ActiveDocument.Pages
        jpgName = PathName & Format(pg.Index, “0#”) & ” ” & pg.Name & “.jpg”
        pg.Export jpgName
    Next
   
    vsoDoc.Close
    vsoApp.Quit
    Set vsoDoc = Nothing
    Set vsoApp = Nothing
 
End Sub

, , , , , , , , , , , , , , , , , , , , , , , ,

2 Comments

Getting Images from Microsoft Office Document Imaging (MODI) with vb.net

Hello! It has been a long time since my last blog post and I am happy to be getting back to this. I have missed writing this blog more than you have missed me I guarantee it!

That being said, now that this blog has resumed there will be a few changes. The landscape has changed a bit since my last blog entry. While I will still focus primarily on vb.net code I will also be including what I am working on that is WPF and C# related as well as other .NET related topics. Why? Simply because as my skillset has expanded I wanted to share what I have learned and am learning with you as well. I hope you won’t mind!

Today’s topic revolves around getting images from Microsoft Office Document Imaging (MODI). As you recall I have done a lot of Office automation over the years and I was asked to do this for a friend. As I said, it is good to be back!

add a reference -> Com -> Microsoft Office Document Imaging

Private Sub ConvertMdi2Tif(ByVal ModiFilePath As String)
Dim miDoc As New MODI.Document
Dim myViewer As New MODI.MiDocView
Dim myImg As MODI.Image
Try
Dim Folder As New DirectoryInfo(ModiFilePath)
pbReportGenerate.Minimum = 0
pbReportGenerate.Maximum = Folder.GetFiles(“*.MDI”).Length
pbReportGenerate.Step = 1
pbReportGenerate.Value = pbReportGenerate.Minimum
For Each File As FileInfo In Folder.GetFiles(“*.MDI”)
miDoc.Create(File.FullName)
myViewer.Document = miDoc
For i As Long = 0 To miDoc.Images.Count – 1
Dim tempDoc As New MODI.Document
myImg = miDoc.Images(i)
tempDoc.Create()
tempDoc.Images.Add(myImg, Nothing)
tempDoc.SaveAs(TIFPath & “\” + GetFileNameWithoutExtension(File.FullName) & i & “.Tif”, MiFILE_FORMAT.miFILE_FORMAT_TIFF_LOSSLESS, MiCOMP_LEVEL.miCOMP_LEVEL_HIGH)
tempDoc.Close()
tempDoc = Nothing
Exit For
Next
pbReportGenerate.PerformStep()
Application.DoEvents()
Next
miDoc.Close()
miDoc = Nothing
myViewer.Document = Nothing
myViewer = Nothing
Catch ex As Exception
MsgBox(ex.Message)
End Try
GC.Collect()
End Sub

Private Sub ConvertTif2Bmp(ByVal TIFFilePath As String)
Dim Folder As New DirectoryInfo(TIFFilePath)
Dim index As Long = 0
pbReportGenerate.Minimum = 0
pbReportGenerate.Maximum = Folder.GetFiles(“*.TIF”).Length
pbReportGenerate.Step = 1
pbReportGenerate.Value = pbReportGenerate.Minimum
For Each File As FileInfo In Folder.GetFiles(“*.TIF”)
GC.WaitForPendingFinalizers()
Dim streamBinary As New FileStream(File.FullName, FileMode.Open)
Dim g As System.Drawing.Image = System.Drawing.Image.FromStream(streamBinary)
Dim imgOutput As New Bitmap(g, g.Width, g.Height)

Dim qualityEncoder As Encoder = Encoder.Quality
Dim ratio As EncoderParameter = New EncoderParameter(qualityEncoder, 40)
Dim codecParams As New EncoderParameters(1)
codecParams.Param(0) = ratio
‘bmp.Save(fileName, jpegCodecInfo, codecParams)
Dim encoder1 As ImageCodecInfo = GetEncoderInfo(“image/bmp”)
imgOutput.Save(BMPPath + “\” + GetFileNameWithoutExtension(File.FullName) + “.” & System.Drawing.Imaging.ImageFormat.Bmp.ToString, encoder1, codecParams)
streamBinary.Close()
streamBinary = Nothing
g.Dispose()
g = Nothing
imgOutput.Dispose()
imgOutput = Nothing
pbReportGenerate.PerformStep()
Application.DoEvents()
Next
GC.Collect()
End Sub


My Facebook

WordPress Tags: vb.net,Images,Microsoft,Office,Document,MODI,automation,friend,reference,MiDocView,Image,Folder,DirectoryInfo,Minimum,Maximum,GetFiles,Length,Step,Value,File,FileInfo,Create,FullName,Long,Count,SaveAs,TIFPath,GetFileNameWithoutExtension,MiFILE_FORMAT,MiCOMP_LEVEL,Close,Exit,PerformStep,Application,DoEvents,Catch,Exception,MsgBox,Message,Collect,TIFFilePath,index,WaitForPendingFinalizers,FileStream,FileMode,Open,System,FromStream,Bitmap,Width,Encoder,ratio,EncoderParameter,EncoderParameters,Param,Save,ImageCodecInfo,GetEncoderInfo,BMPPath,ImageFormat,Dispose,blog,miDoc,myViewer,myImg,pbReportGenerate,tempDoc,streamBinary,imgOutput,qualityEncoder,codecParams

, , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , , ,

2 Comments

Print Barcode Labels with vb.net

Good afternoon everyone! I had an extremely quiet evening last night and this morning. We are really at crunch time at work right now but I think I am where I need to be with what I need to do.

Anyway, today’s topic is one that can throw a lot of for fits. We need to print barcode labels but some characters don’t translate as you would expect in print. So this class is a little old but it still works. Make it a great day!

 

Imports System.Drawing.Printing
Imports System.Drawing.Graphics
Public Class Form1
    Inherits System.Windows.Forms.Form
    Private WithEvents BarcodeDoc As barcode.TextPrint ‘BarcodingParts.TextPrint

#Region " Windows Form Designer generated code "

    Public Sub New()
        MyBase.New()

        ‘This call is required by the Windows Form Designer.
        InitializeComponent()

        ‘Add any initialization after the InitializeComponent() call

    End Sub

    ‘Form overrides dispose to clean up the component list.
    Protected Overloads Overrides Sub Dispose(ByVal disposing As Boolean)
        If disposing Then
            If Not (components Is Nothing) Then
                components.Dispose()
            End If
        End If
        MyBase.Dispose(disposing)
    End Sub

    ‘Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    ‘NOTE: The following procedure is required by the Windows Form Designer
    ‘It can be modified using the Windows Form Designer. 
    ‘Do not modify it using the code editor.
    Friend WithEvents PrintDocument1 As System.Drawing.Printing.PrintDocument
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents PrintPreviewDialog1 As System.Windows.Forms.PrintPreviewDialog
    <System.Diagnostics.DebuggerStepThrough()> Private Sub InitializeComponent()
        Dim resources As System.Resources.ResourceManager = New System.Resources.ResourceManager(GetType(Form1))
        Me.PrintDocument1 = New System.Drawing.Printing.PrintDocument
        Me.Button1 = New System.Windows.Forms.Button
        Me.PrintPreviewDialog1 = New System.Windows.Forms.PrintPreviewDialog
        Me.SuspendLayout()
        ‘
        ‘Button1
        ‘
        Me.Button1.Location = New System.Drawing.Point(196, 224)
        Me.Button1.Name = "Button1"
        Me.Button1.TabIndex = 0
        Me.Button1.Text = "Button1"
        ‘
        ‘PrintPreviewDialog1
        ‘
        Me.PrintPreviewDialog1.AutoScrollMargin = New System.Drawing.Size(0, 0)
        Me.PrintPreviewDialog1.AutoScrollMinSize = New System.Drawing.Size(0, 0)
        Me.PrintPreviewDialog1.ClientSize = New System.Drawing.Size(400, 300)
        Me.PrintPreviewDialog1.Enabled = True
        Me.PrintPreviewDialog1.Icon = CType(resources.GetObject("PrintPreviewDialog1.Icon"), System.Drawing.Icon)
        Me.PrintPreviewDialog1.Location = New System.Drawing.Point(132, 132)
        Me.PrintPreviewDialog1.MinimumSize = New System.Drawing.Size(375, 250)
        Me.PrintPreviewDialog1.Name = "PrintPreviewDialog1"
        Me.PrintPreviewDialog1.TransparencyKey = System.Drawing.Color.Empty
        Me.PrintPreviewDialog1.Visible = False
        ‘
        ‘Form1
        ‘
        Me.AutoScaleBaseSize = New System.Drawing.Size(5, 13)
        Me.ClientSize = New System.Drawing.Size(292, 266)
        Me.Controls.Add(Me.Button1)
        Me.Name = "Form1"
        Me.Text = "Form1"
        Me.ResumeLayout(False)

    End Sub

#End Region
    Private Sub Button1_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button1.Click
        ‘ BarcodeDoc = New BarcodingParts.TextPrint("*00417955*", "Here is Second line from Extended Barcode")
        ‘ BarcodeDoc.Font = New Font("FREE 3 OF 9 Extended", 30) ‘<—- Free Font on the internet or add your own
        ‘ OR USE THIS
        BarcodeDoc = New TextPrint("*00417 955*", "Here is Second line from Regular Barcode")
        BarcodeDoc.Font = New Font("FREE 3 OF 9", 30) ‘<—- Free Font on the internet or add your own
        ‘For Pre-veiw Printing
        PrintPreviewDialog1.Document = BarcodeDoc
        PrintPreviewDialog1.ShowDialog()

        ‘For Direct Printing
        Dim PrintDialog1 As New PrintDialog
        ‘PrintDialog1.Document = BarcodeDoc
        ‘PrintDocument1.Print()
    End Sub
    Private Sub PrintDocument1_PrintPage(ByVal sender As Object, ByVal e As System.Drawing.Printing.PrintPageEventArgs) Handles PrintDocument1.PrintPage
        BarcodeDoc.PrinterSettings.PrinterName = InitializeDefaultPrinter() ‘"Zebra"
        BarcodeDoc.DefaultPageSettings.Margins.Left = 10
        BarcodeDoc.DefaultPageSettings.Margins.Right = 10
        BarcodeDoc.DefaultPageSettings.Margins.Top = 40
    End Sub
#Region " Initialize Default Printer "
    Public Function InitializeDefaultPrinter()
        ‘ Set the specified printer to the default printer for this program. Return
        ‘ true if the printer was found.

        Dim objprinter As PageSettings = New PageSettings
        Dim strname = objprinter.PrinterSettings.PrinterName

        InitializeDefaultPrinter = strname
    End Function
#End Region
End Class

‘CLASS FILE

Public Class TextPrint
    ‘ Inherits all the functionality of a PrintDocument
    Inherits Printing.PrintDocument
    ‘ Private variables to hold default font and text
    Private fntPrintFont As Font
    Private strText As String
    Private strText2 As String
    Private PrintBarCodeText As String
    Public Sub New(ByVal Text As String, ByVal Text2 As String)
        ‘ Sets the file stream
        MyBase.New()
        strText = Text
        strText2 = Text2
    End Sub
    Public Property Text() As String
        Get
            Return strText
        End Get
        Set(ByVal Value As String)
            strText = Value
        End Set
    End Property
    Public Property Text2() As String
        Get
            Return Trim(strText2)
        End Get
        Set(ByVal Value As String)
            strText2 = Trim(Value)
        End Set
    End Property
    Public Property CodeText() As String
        Get
            PrintBarCodeText = Trim(Replace(strText, "*", " "))
            Return PrintBarCodeText
        End Get
        Set(ByVal Value As String)
            If PrintBarCodeText = "" Then
                PrintBarCodeText = Trim(Replace(Value, "*", " "))
            End If
            PrintBarCodeText = Value
        End Set
    End Property
    Protected Overrides Sub OnBeginPrint(ByVal ev As Printing.PrintEventArgs)
        ‘ Run base code
        MyBase.OnBeginPrint(ev)
        ‘ Sets the default font
        If fntPrintFont Is Nothing Then
            fntPrintFont = New Font("Times New Roman", 12)
        End If
    End Sub
    Public Property Font() As Font
        ‘ Allows the user to override the default font
        Get
            Return fntPrintFont
        End Get
        Set(ByVal Value As Font)
            fntPrintFont = Value
        End Set
    End Property
    Protected Overrides Sub OnPrintPage(ByVal ev As Printing.PrintPageEventArgs)
        ‘ Provides the print logic for our document

        ‘ Run base code
        MyBase.OnPrintPage(ev)
        ‘ Variables
        Static intCurrentChar As Integer
        Dim intPrintAreaHeight, intPrintAreaWidth, intMarginLeft, intMarginTop As Integer
        ‘ Set printing area boundaries and margin coordinates
        With MyBase.DefaultPageSettings
            intPrintAreaHeight = .PaperSize.Height – .Margins.Top – .Margins.Bottom
            intPrintAreaWidth = .PaperSize.Width – .Margins.Left – .Margins.Right
            intMarginLeft = .Margins.Left ‘X
            intMarginTop = .Margins.Top   ‘Y
        End With
        ‘ If Landscape set, swap printing height/width
        If MyBase.DefaultPageSettings.Landscape Then
            Dim intTemp As Integer
            intTemp = intPrintAreaHeight
            intPrintAreaHeight = intPrintAreaWidth
            intPrintAreaWidth = intTemp
        End If
        ‘ Calculate total number of lines
        Dim intLineCount As Int32 = CInt(intPrintAreaHeight / Font.Height)
        ‘ Initialise rectangle printing area
        Dim rectPrintingArea As New RectangleF(intMarginLeft, intMarginTop, intPrintAreaWidth, intPrintAreaHeight)
        ‘ Initialise StringFormat class, for text layout
        Dim objSF As New StringFormat(StringFormatFlags.LineLimit)
        ‘ Figure out how many lines will fit into rectangle
        Dim intLinesFilled, intCharsFitted As Int32
        Dim stringSize As New SizeF
        stringSize = ev.Graphics.MeasureString(Mid(strText, _
                    UpgradeZeros(intCurrentChar)), Font, New SizeF(intPrintAreaWidth, _
                    intPrintAreaHeight), objSF, intCharsFitted, intLinesFilled)
        ‘ Print the text to the page
        ev.Graphics.DrawString(Mid(strText, _
            UpgradeZeros(intCurrentChar)), Font, Brushes.Black, rectPrintingArea, objSF)

        ‘ Initialise rectangle printing area for the Barcode Text
        Dim stringFont As New Font("Arial", 12, FontStyle.Bold)
        Dim size As SizeF = ev.Graphics.MeasureString(CodeText, stringFont)
        Dim size2 As SizeF = ev.Graphics.MeasureString(strText2, stringFont)
        Dim BCPrintingArea As New RectangleF(stringSize.Width – size.Width / 2, intMarginTop + stringSize.Height, intPrintAreaWidth, intPrintAreaHeight)

        ‘Move Second line to center
        Dim moveStr As Integer
        moveStr = stringSize.Width – size2.Width / 2
        moveStr = intMarginLeft + (moveStr / intMarginLeft)
        Dim BCPrintingArea2 As New RectangleF(moveStr, intMarginTop + stringSize.Height + size2.Height, intPrintAreaWidth, intPrintAreaHeight)

        ‘ADD text Bottom of Barcode
        ev.Graphics.DrawString(CodeText, stringFont, Brushes.Black, BCPrintingArea)
        ev.Graphics.DrawString(strText2, stringFont, Brushes.Black, BCPrintingArea2)

        ‘ Increase current char count
        intCurrentChar += intCharsFitted
        ‘ Check whether we need to print more
        If intCurrentChar < strText.Length Then
            ev.HasMorePages = True
        Else
            ev.HasMorePages = False
            intCurrentChar = 0
        End If
    End Sub
    Public Function UpgradeZeros(ByVal Input As Integer) As Integer
        ‘ Upgrades all zeros to ones
        ‘ – used as opposed to defunct IIF or messy If statements
        If Input = 0 Then
            Return 1
        Else
            Return Input
        End If
    End Function

End Class

Technorati Tags: ,,,,,,,,,,,,,,,,,
,,,,,,,,,,,
,,,,,,,,,
,,,,,,,,,,,,
,,,,,,,,,,,,
,,,,,,,,,,,,,
,,,,,,,,,,,
,,,,,,,,,,,,,,,
,,,,,,,,,,,,,
,,,,,,,,,

1 Comment