I'm solving an issue where I need to create one PDF form.
That PDF form has 8 sections where I need to put info about and looks like shown on picture (only 4 shown).
The point is that my query will return 0 - n different results. So I need to split by 8 and post on different pages.
I tried like shown below but that seems not to work since I always load a new document. Does anyone have some advice how to make it?
Try
Dim sCommand As OleDb.OleDbCommand
sCommand = New OleDb.OleDbCommand("SELECT a,b,c Query to fetch n results ", _dbCon)
sCommand.CommandTimeout = 0
Dim _dbREADER As OleDb.OleDbDataReader
_dbREADER = sCommand.ExecuteReader
Dim dt As DataTable = New DataTable()
dt.Load(_dbREADER)
Dim totalPages As Integer = dt.Rows.Count / 8
Dim currentPage As Integer = 1
Dim rowCounter As Long = 0
If dt.Rows.Count > 0 Then
For Each row In dt.Rows
rowCounter += 1
If rowCounter = 8 Then
currentPage += 1
rowCounter = 0
End If
_pdfDocumentOutput = System.IO.Path.GetTempPath() & "MailingForm_" & currentPage & ".pdf"
SaveFromResources(_pdfDocument, My.Resources.template)
Using reader As New PdfReader(_pdfDocument)
Using stamper As New PdfStamper(reader, New IO.FileStream(_pdfDocumentOutput, IO.FileMode.Create))
Dim fontName As String = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "SCRIPTIN.ttf")
Dim bf As BaseFont = BaseFont.CreateFont(fontName, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED)
Dim pdfForm As AcroFields = stamper.AcroFields
pdfForm.AddSubstitutionFont(bf)
pdfForm.SetField(rowCounter - 1 & "0", row("Customer")) 'Checks the top radiobutton of the VrPr4 field
pdfForm.SetField(rowCounter - 1 & "1", row("Address"))
pdfForm.SetField(rowCounter - 1 & "2", row("Location"))
stamper.FormFlattening = True
End Using
End Using
Next
End If
Status.Text = "Store info loaded ! "
Catch ex As Exception
Status.Text = ex.Message
End Try
I found the solution by splitting tables
Private Shared Function SplitTable(ByVal originalTable As DataTable, ByVal batchSize As Integer) As List(Of DataTable)
Dim tables As List(Of DataTable) = New List(Of DataTable)()
Dim i As Integer = 0
Dim j As Integer = 1
Dim newDt As DataTable = originalTable.Clone()
newDt.TableName = "Table_" & j
newDt.Clear()
For Each row As DataRow In originalTable.Rows
Dim newRow As DataRow = newDt.NewRow()
newRow.ItemArray = row.ItemArray
newDt.Rows.Add(newRow)
i += 1
If i = batchSize Then
tables.Add(newDt)
j += 1
newDt = originalTable.Clone()
newDt.TableName = "Table_" & j
newDt.Clear()
i = 0
End If
If row.Equals(originalTable.Rows(originalTable.Rows.Count - 1)) Then
tables.Add(newDt)
j += 1
newDt = originalTable.Clone()
newDt.TableName = "Table_" & j
newDt.Clear()
i = 0
End If
Next
Return tables
End Function
And after that loop through each one of table . And put all results to one file
Dim tables = SplitTable(dt, 8)
Related
I need to write 50 million records with 72 columns into text file, the file size is growing as 9.7gb .
I need to check each and every column length need to format as according to the length as defined in XML file.
Reading records from oracle one by one and checking the format and writing into text file.
To write 5 crores records it is taking more than 24 hours. how to increase the performance in the below code.
Dim valString As String = Nothing
Dim valName As String = Nothing
Dim valLength As String = Nothing
Dim valDataType As String = Nothing
Dim validationsArray As ArrayList = GetValidations(Directory.GetCurrentDirectory() + "\ReportFormat.xml")
Console.WriteLine("passed xml")
Dim k As Integer = 1
Try
Console.WriteLine(System.DateTime.Now())
Dim selectSql As String = "select * from table where
" record_date >= To_Date('01-01-2014','DD-MM-YYYY') and record_date <= To_Date('31-12-2014','DD-MM-YYYY')"
Dim dataTable As New DataTable
Dim oracleAccess As New OracleConnection(System.Configuration.ConfigurationManager.AppSettings("OracleConnection"))
Dim cmd As New OracleCommand()
cmd.Connection = oracleAccess
cmd.CommandType = CommandType.Text
cmd.CommandText = selectSql
oracleAccess.Open()
Dim Tablecolumns As New DataTable()
Using oracleAccess
Using writer = New StreamWriter(Directory.GetCurrentDirectory() + "\FileName.txt")
Using odr As OracleDataReader = cmd.ExecuteReader()
Dim sbHeaderData As New StringBuilder
For i As Integer = 0 To odr.FieldCount - 1
sbHeaderData.Append(odr.GetName(i))
sbHeaderData.Append("|")
Next
writer.WriteLine(sbHeaderData)
While odr.Read()
Dim sbColumnData As New StringBuilder
Dim values(odr.FieldCount - 1) As Object
Dim fieldCount As Integer = odr.GetValues(values)
For i As Integer = 0 To fieldCount - 1
Dim vals As Array = validationsArray(i).ToString.ToUpper.Split("|")
valName = vals(0).trim
valDataType = vals(1).trim
valLength = vals(2).trim
Select Case valDataType
Case "VARCHAR2"
If values(i).ToString().Length = valLength Then
sbColumnData.Append(values(i).ToString())
'sbColumnData.Append("|")
ElseIf values(i).ToString().Length > valLength Then
sbColumnData.Append(values(i).ToString().Substring(0, valLength))
'sbColumnData.Append("|")
Else
sbColumnData.Append(values(i).ToString().PadRight(valLength))
'sbColumnData.Append("|")
End If
Case "NUMERIC"
valLength = valLength.Substring(0, valLength.IndexOf(","))
If values(i).ToString().Length = valLength Then
sbColumnData.Append(values(i).ToString())
'sbColumnData.Append("|")
Else
sbColumnData.Append(values(i).ToString().PadLeft(valLength, "0"c))
'sbColumnData.Append("|")
End If
'sbColumnData.Append((values(i).ToString()))
End Select
Next
writer.WriteLine(sbColumnData)
k = k + 1
Console.WriteLine(k)
End While
End Using
writer.WriteLine(System.DateTime.Now())
End Using
End Using
Console.WriteLine(System.DateTime.Now())
'Dim Adpt As New OracleDataAdapter(selectSql, oracleAccess)
'Adpt.Fill(dataTable)
Return Tablecolumns
Catch ex As Exception
Console.WriteLine(System.DateTime.Now())
Console.WriteLine("Error: " & ex.Message)
Console.ReadLine()
Return Nothing
End Try
I have been using ITextSharp to replicate the information on a webpage so that the information on the page can be printed in PDF format.
I generate my table by using the following code.
Protected Sub GenerateTable(noOfRows As Integer, reader As SqlClient.SqlDataReader)
Dim table As Table
Dim row As TableRow
Dim cell As TableCell
Dim lbl As Label
Dim lblVolume As Label
Dim lblUnitPrice As Label
Dim lblTotalPrice As Label
table = VolumeTable
table.ID = "VolumeTable"
'Page.Form.Controls.Add(table)
For i As Integer = 1 To noOfRows Step 1
row = New TableRow()
For j As Integer = 0 To 5 Step 1
cell = New TableCell()
If j = 1 Then
lblVolume = New Label()
lblVolume.ID = "LabelRow_" & i & "Col_" & j
cell.Controls.Add(lblVolume)
lblVolume.Text = reader.GetValue(2)
ElseIf j = 2 Then
lblUnitPrice = New Label()
lblUnitPrice.ID = "UnitLabel" & i
lblUnitPrice.Text = "Unit Price: "
cell.Controls.Add(lblUnitPrice)
ElseIf j = 3 Then
lblUnitPrice = New Label()
lblUnitPrice.ID = "LabelRow_" & i & "Col_" & j
cell.Controls.Add(lblUnitPrice)
lblUnitPrice.Text = reader.GetValue(5)
ElseIf j = 4 Then
lblUnitPrice = New Label()
lblUnitPrice.ID = "TotalPrice" & i
lblUnitPrice.Text = "Total Price: "
cell.Controls.Add(lblUnitPrice)
ElseIf j = 5 Then
lblTotalPrice = New Label()
lblTotalPrice.ID = "LabelRow_" & i & "Col_" & j
cell.Controls.Add(lblTotalPrice)
lblTotalPrice.Text = reader.GetValue(6)
ElseIf j = 0 Then
lbl = New Label()
lbl.ID = "Label" & i
lbl.Text = "Volume " & i
cell.Controls.Add(lbl)
End If
row.Cells.Add(cell)
Next
table.Rows.Add(row)
reader.Read()
Next
'SetPreviousTableData(noOfRows)
ViewState("RowsCount") = noOfRows
Session("RowsCount") = noOfRows
End Sub
How would I go about replicating this table in ITextSharp using Visual Basic. All of the solutions I have looked at so far have been in C# but I cant figure out to do this in VB
any advice would be appreciated.
Below is the most basic usage of iTextSharp in VB.Net. I'm not binding it to any data model, just two loops for rows and columns since it seems like you've got that part down. See the code comments for more details.
''//Filename that we're going to write to
Dim FileName = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "Test.pdf")
''//Create a Stream to write to. This could also be a MemoryStream or anything else that inherits from System.IO.Stream
Using FS As New FileStream(FileName, FileMode.Create, FileAccess.Write, FileShare.None)
''//Create an abstract PDF document
Using Doc As New Document()
''//Create a PdfWriter that binds the abstraction to the stream
Using Writer = PdfWriter.GetInstance(Doc, FS)
''//Open the document to allow writing
Doc.Open()
''//Create a Pdf table with 4 columns
Dim table As New PdfPTable(4)
''//Loop through 10 rows
For RowNumber = 1 To 10
''//Loop through 4 columns
For ColumnNumber = 1 To 4
''//Write some text to the table
table.AddCell(New Paragraph(String.Format("Hello from {0}x{1}", RowNumber, ColumnNumber)))
Next
Next
''//Add the table to the document
Doc.Add(table)
''//Close the document to disable writing and flush buffers
Doc.Close()
End Using
End Using
End Using
So, quite simple.
I am importing CSVs into a datagrid, though the csv always has to have a variable amount of columns.
For 3 Columns, I use this code:
Dim sr As New IO.StreamReader("E:\test.txt")
Dim dt As New DataTable
Dim newline() As String = sr.ReadLine.Split(";"c)
dt.Columns.AddRange({New DataColumn(newline(0)), _
New DataColumn(newline(1)), _
New DataColumn(newline(2))})
While (Not sr.EndOfStream)
newline = sr.ReadLine.Split(";"c)
Dim newrow As DataRow = dt.NewRow
newrow.ItemArray = {newline(0), newline(1), newline(2)}
dt.Rows.Add(newrow)
End While
DG1.DataSource = dt
This works perfectly. But how do I count the number of "newline"s ?
Can I issue a count on the number of newlines somehow? Any other example code doesn't issue column heads.
If my csv file has 5 columns, I would need an Addrange of 5 instead of 3 and so on..
Thanks in advance
Dim sr As New IO.StreamReader(path)
Dim dt As New DataTable
Dim newline() As String = sr.ReadLine.Split(","c)
' MsgBox(newline.Count)
' dt.Columns.AddRange({New DataColumn(newline(0)),
' New DataColumn(newline(1)),
' New DataColumn(newline(2))})
Dim i As Integer
For i = 0 To newline.Count - 1
dt.Columns.AddRange({New DataColumn(newline(i))})
Next
While (Not sr.EndOfStream)
newline = sr.ReadLine.Split(","c)
Dim newrow As DataRow = dt.NewRow
newrow.ItemArray = {newline(0), newline(1)}
dt.Rows.Add(newrow)
End While
dgv.DataSource = dt
End Sub
Columns and item values can be added to a DataTable individually, using dt.Columns.Add and newrow.Item, so that these can be done in a loop instead of hard-coding for a specific number of columns. e.g. (this code assumes Option Infer On, so adjust as needed):
Public Function CsvToDataTable(csvName As String, Optional delimiter As Char = ","c) As DataTable
Dim dt = New DataTable()
For Each line In File.ReadLines(csvName)
If dt.Columns.Count = 0 Then
For Each part In line.Split({delimiter})
dt.Columns.Add(New DataColumn(part))
Next
Else
Dim row = dt.NewRow()
Dim parts = line.Split({delimiter})
For i = 0 To parts.Length - 1
row(i) = parts(i)
Next
dt.Rows.Add(row)
End If
Next
Return dt
End Function
You could then use it like:
Dim dt = CsvToDataTable("E:\test.txt", ";"c)
DG1.DataSource = dt
so I have a csv file that has extra commas in it. I know I won't ever need anything after a specific column. So basically any information after column 12 I won't need. I don't have a say on how the csv looks when it gets to me, so I can't change it there. I was wondering if there is a way to just read the first 12 columns and ignore the rest of the csv file.
this is what the code looks like now.
thank you for any help
Private Sub GetData(ByVal Path As String, ByRef DG As DataGridView, Optional ByVal NoHeader As Boolean = False)
Dim Fields(100) As String
Dim Start As Integer = 1
If NoHeader Then Start = 0
If Not File.Exists(Path) Then
Return
End If
Dim Lines() As String = File.ReadAllLines(Path)
Lines(0) = Lines(0).Replace(Chr(34), "")
Fields = Lines(0).Split(",")
If NoHeader Then
For I = 1 To Fields.Count - 1
Fields(I) = Str(I)
Next
End If
dt = New DataTable()
For Each Header As String In Fields
dt.Columns.Add(New DataColumn(Header.Trim()))
Dim desiredSize As Integer = 11
While dt.Columns.Count > desiredSize
dt.Columns.RemoveAt(desiredSize)
End While
Next
For I = Start To Lines.Count - 1
Lines(I) = Lines(I).Replace(Chr(34), "")
Fields = Lines(I).Split(",")
Dim dr As DataRow = dt.Rows.Add()
For j = 0 To Fields.Count - 1
dr(j) = Fields(j).Trim()
Next
Next
DG.DataSource = dt
End Sub
Really all you need to do is, in the for loop where you iterate through Fields at the bottom, replace For j = 0 to Fields.Count - 1 with For j = 0 to 11.
I'm still a student without much experience using vb.net and I am having some trouble splitting a string within an array into 2 values. For example in my textbox I have several lines of measurements that are Length x Width: 20x14, 10x8, 16x13. Each measurement is on its own line. I'm trying to split all Width values that are greater than 12 into 2 separate measurements, so with that last example, I would have 5 measurements (LxW): 20x12, 20x2, 10x8, 16x12, 16x1, then I would like to add these measurements to a new textbox with each measurement on its own line.
Here is the code I have so far. Again, I am very new to programming and this is the first serious project for me since "Hello World", so what I have might be way off. Thanks in advance.
Dim room As String = RoomsTextBox.Text
If room.EndsWith(vbCrLf) Then room = room.Substring(0, room.Length - vbCrLf.Length)
Dim roomarray() As String = room.Split(vbCrLf)
Dim Cuts(roomarray.Length - 1, 0) As String
RoomsTextBox.Select(0, 0)
Dim CutLength As Integer
Dim CutWidth As Integer
Dim i As Integer
Dim j As Integer
CutsTextBox.Select()
Cuts(i, j) = (Val(roomarray(i).Split("x")(0))) & Val(roomarray(j).Split("x")(1))
For i = 0 To Cuts.GetUpperBound(0)
For j = 0 To Cuts.GetUpperBound(1)
Cuts(i, j) = 0
Next
If Val(roomarray(i)) > 12 Then
CutWidth = Val(roomarray(i)) - 12
CutLength = Val(roomarray(j))
Else
CutWidth = Val(roomarray(i))
CutLength = Val(roomarray(j))
End If
Dim inserttext = CutsTextBox.Text
Dim insertposition As Integer = CutsTextBox.SelectionStart
CutsTextBox.Text = CutsTextBox.Text.Insert(0, CutLength.ToString & "x" & _
CutWidth.ToString)
CutsTextBox.SelectionStart = insertposition + inserttext.Length
Next i
I even tried it with inserting the measurements into a ListBox. Here is the code for that:
Dim room As String = RoomsTextBox.Text
Dim roomarray() As String = room.Split(vbCrLf)
Dim Cuts(roomarray.Length - 1, 0) As String
Dim CutLength As Integer
Dim CutWidth As Integer
Dim i As Integer
Dim j As Integer
CutsTextBox.Select()
Cuts(i, j) = (Val(roomarray(i).Split("x")(0))) & Val(roomarray(j).Split("x")(1))
For i = 0 To Cuts.GetUpperBound(0)
For j = 0 To Cuts.GetUpperBound(1)
Cuts(i, j) = 0
Next
If Val(roomarray(i)) > 12 Then
CutWidth = Val(roomarray(i)) - 12
CutLength = Val(roomarray(j))
Else
CutWidth = Val(roomarray(i))
CutLength = Val(roomarray(j))
End If
ListBox1.Items.Add(CutLength.ToString & "x" & CutWidth.ToString)
Next i
Try this out.
Dim dimensions As String() = txtInput.Text.Split(vbCrLf)
Dim final As New List(Of String)
For Each item In dimensions
Dim lw As String() = item.Split("x")
Dim length As String = lw(0)
Dim width As Integer = CInt(lw(1))
If width > 12 Then
Dim new1 As String
Dim new2 As String
new1 = length & "x" & (width - 12).ToString
new2 = length & "x12"
final.Add(new1)
final.Add(new2)
Else
final.Add(item)
End If
Next
For Each item In final
txtOutPut.Text += item & vbCrLf
Next