Auto-Breakline PdfTable Cells PdfFileWriter c# - c#

Im writing a Programm that retrieves Cutomer Data from a SQLite-File and stores them in a PDF-File in a PdfTable like:
PdfContents contentsTable = new PdfContents(page);
PdfTable table = new PdfTable(page, contentsTable, ArialNormal, fontSize);
table.TableArea = new PdfRectangle(border (2 * border + fontHight), (210 - border), (297 - (2 * border + 4 * linespacing + 5 * fontHight))); // <- 'border', 'fontHight' and 'linespacing' are simply variables i use to define lengths that also apear at other locations
table.SetColumnWidth(30, 75, 35, 10, 30, 22, 8);
table.HeaderOnEachPage = true;
table.MinRowHight = 5;
table.Header[0].Style = table.HeaderStyle;
table.Header[1].Style = table.HeaderStyle;
table.Header[2].Style = table.HeaderStyle;
table.Header[3].Style = table.HeaderStyle;
table.Header[4].Style = table.HeaderStyle;
table.Header[5].Style = table.HeaderStyle;
table.Header[6].Style = table.HeaderStyle;
table.Header[0].Value = "CODE";
table.Header[1].Value = "BESCHREIBUNG";
table.Header[2].Value = "MATERIALNAME";
table.Header[3].Value = "NoFl";
table.Header[4].Value = "ERGEBNIST";
table.Header[5].Value = "BEWERTUNG";
table.Header[6].Value = "ART";
// Querys the 'ANALYT' and 'RESULTS' Table and Adds the Answers into the Table in the PDF-File
using (var connection = new SQLiteConnection("Data Source = " + dbFile)) // <- 'dbFile' contains the Path to the File
{
// Opens the connection to the SQLite File
connection.Open();
var command = connection.CreateCommand();
command.CommandText = "select A.CODE, A.BESCHERIBUNG, A.MATERIALNAME, R.NORMFLAG, R.ERGEBNIST, R.BEWERTUNG, R.ART " +
"from ANALYT A, RESULTS R " +
"and A.ANALYTX = R.ANALYTX " +
"order by A.MATERIALNAME desc, R.SORT ";
using (var reader = command.ExecuteReader())
{
if (reader.HasRows)
{
while (reader.Read())
{
table.Cell[0].Value = reader[0].ToString();
table.Cell[1].Value = reader[1].ToString();
table.Cell[2].Value = reader[2].ToString();
table.Cell[3].Value = reader[3].ToString();
table.Cell[4].Value = reader[4].ToString();
table.Cell[5].Value = reader[5].ToString();
table.Cell[6].Value = reader[6].ToString();
}
contentToBeAdded = true; // <- A variable i use to determine if the processes are all successfull
}
else
{
// Code that lets the user know something went wrong
}
connection.Close();
}
table.Close();
document.CreateFile();
This code works perfectly fine in almost all circumstances, but as the entrences in the Database have been collected by hundreds of people over decades, so the data values can have a wide range in length. While the Width-VAlues i entered are adequate for most situations, there can be specific entrenceses that are far longer. As the data i work with is rather critical, I cant just ignore these few cases.
My original thought was that the PdfTable would automatically Benter a new line and make the Cell higher. But when i ran into this exact problem in my testing, I noticed that the Text just kept going and was covering the next cell.
Is there an easy fix that i can tell PdfTable to do this automatically or do i have to count the number of letters in the string and devide it maually for every value that is to long?
Since I am still rather a beginner in programming, I greatly appreciate any help and input.

I've found the solution to my question and its actually quite simple. I hope that in the future someone might have the same problem and find this helpful.
Instead of adding a simple string, use PdfFileWriter.TextBox like:
PdfFileWriter.TextBox textBox0 = new PdfFileWriter.TextBox(16, 0, 0.5); // <- 16 = TextboxWidth, 0 = FirstLineIndent, 0.5 = LineBreakFactor
textBox0.AddText(ArialNormal, fontSize, reader0); // <- ArialNormal = PdfFont Variable containing a Font, fontSize = int Variable containing the Font Size, reader0 = string Variable containing the Content
table.Cell[0].Value = textBox0;
This will add the Text, AutoLineBreak and increase the Height of the Cell.
Hope anyone finds this helpful.

Related

My database query is only querying the last element of my array

My problem in the title i have allcodes array and codes TextBox (kodTxtBox)
i will split textbox like line per element and querying all elements with for loop then
when i run it, it shows the query of only the last element of the allcodes array with the
messagebox, but the others go into else and giving error message box
some turkish words in my codes so.
aciklama = description
birim = monad
birimFiyat = Price per 1 unit
ürünler = products
ürünler.sipariskod = products.ordercode etc.
i did a lot of ways for this i used foreach all variables type is string
allCodes = kodTxtBox.Text.Split('\n');
for (int i = 0; i < allCodes.Length; i++)
{
queryString = "SELECT ürünler.siparisKod, ürünler.aciklama, ürünler.birim, ürünler.fGrup, ürünler.birimfiyat FROM ürünler WHERE (((ürünler.siparisKod)=\"" + allCodes[i] + "\"));";
using (OleDbCommand query = new OleDbCommand(queryString))
{
query.Connection = connection;
reader = query.ExecuteReader();
if (reader.Read())
{
MessageBox.Show(allCodes[i] + " Succesful");
var desc = reader["aciklama"].ToString();
var monad = reader["birim"].ToString();
var sellPrice = reader["birimFiyat"].ToString();
MessageBox.Show("Açıklama: " + desc + " Birim: " + monad + " Satış Fiyatı: " + sellPrice);
reader.Close();
}
else
{
MessageBox.Show("Hata");
}
}
}
I solved the problem by making a single query instead of multiple queries. I saved the values ​​returned in each single query into a list and at the end I made the necessary for loop using the elements of the list

out of memory exception with grid in scrollviewer

I am very new in developing apps with C# for WP 8.1 Silverlight.
I developed an app to display data from a csv-file.
The data is displayed in a grid within a scrollviewer element with 7 columns.
All works fine. But when the app gets more then 600 lines from the csv-file the app crashes with an out of Memory exception.
How can I avoid this? It should be no problem to display 600 lines of text in a grid.
See my code:
//insert lines:
//Row create:
reihe1 = new RowDefinition();
reihe1.Height = new GridLength(zeilenhoehe);
grid_umsatzdetail.RowDefinitions.Add(reihe1);
reihe1 = null;
//Columns create:
//first column date:
textblock_name = dateizeile + "|" + index_daten + "|" + "0";
TextBlock textblock_new_datum = new TextBlock();
textblock_new_datum.Name = textblock_name;
textblock_new_datum.Height = zeilenhoehe;
textblock_new_datum.Width = Double.NaN;
textblock_new_datum.FontSize = schriftgroesse;
textblock_new_datum.Text = " " + teile[0] + " ";
Grid.SetRow(textblock_new_datum, zaehler_reihe);
Grid.SetColumn(textblock_new_datum, 0);
grid_umsatzdetail.Children.Add(textblock_new_datum);
textblock_new_datum = null;
//border insert into grid:
rand = new Border();
rand.BorderThickness = new Thickness(1);
rand.BorderBrush = new SolidColorBrush(Colors.White);
rand.Width = Double.NaN;
rand.Height = zeilenhoehe_head;
Grid.SetRow(rand, zaehler_reihe);
Grid.SetColumn(rand, 0);
grid_umsatzdetail.Children.Add(rand);
rand = null;
//second column amount:
... same coding as above for every column ...
I am really happy for any tips!

Programatically adding a dynamic number of spaces to a string

I've got a treeview control, which I want to look like this:
Just by messing around with css and a text string, I'm actually pretty close. I just need some help getting over the line.
Here is the code I'm using to generate the treeview:
void FillTree_Parent()
{ // fills the parent view of the Tree Action items
//int RoleID = Convert.ToInt32(ddlRole.SelectedValue);
using (SqlConnection con4 = new SqlConnection(ConfigurationManager.ConnectionStrings["PBRConnectionString"].ConnectionString))
{
try
{
SqlCommand cmd2 = new SqlCommand("SELECT [ACCT_GRP], [ACCT_GRP_PK], [ACTIVE_FLG], [LOAD_BY], [LOAD_TIMESTAMP] FROM [ACCT_GRP_LIST] ORDER BY [ACCT_GRP] ASC", con4);
SqlDataAdapter da = new SqlDataAdapter(cmd2);
DataSet PrSet = new DataSet();
da.Fill(PrSet, "ACCT_GRP");
TreeViewAccts.Nodes.Clear();
foreach (DataRow dr in PrSet.Tables[0].Rows)
{
DateTime date = DateTime.Parse(dr["LOAD_TIMESTAMP"].ToString());
string formatted = date.ToString("MM/dd/yyyy");
TreeNode tnParent = new TreeNode();
// Here is our focus
tnParent.Text = dr["ACCT_GRP"].ToString().Replace("'", "''") +
" ········· " + "Active:" + dr["ACTIVE_FLG"].ToString() +
" ········· " + "Loaded On:" + formatted + "";
//
tnParent.Value = dr["ACCT_GRP_PK"].ToString();
tnParent.PopulateOnDemand = true;
tnParent.SelectAction = TreeNodeSelectAction.SelectExpand;
TreeViewAccts.Nodes.Add(tnParent);
FillTree_Child(tnParent, tnParent.Value);
}
}
catch (Exception ae)
{
Response.Write(ae.Message);
}
}
}
In that block marked "// Here is our focus", what I need to do is figure out how to get that first set of " ········· " to generate a dynamic number of spaces based on the fact that dr["ACCT_GRP"] can have as many as 75 characters. So, I need to determine the length of dr["ACCT_GRP"], subtract that from 75 and then generate that many spaces.
Can anyone help me with this logic? Also, as a bonus question, if anyone could tell me how to use spaces instead of "·"'s I'd appreciate it; whenever I just hit the spacebar a bunch of times and enclose it in quotes, it acts like those spaces don't even exist.
int len = dr["ACCT_GRP"].Length;
int paddingLength = 75 - len;
string padding = new string('.', paddingLength);
I get it from your question that you are viewing this in a browser (you mentioned CSS). HTML spec tells the browser to collapse all consecutive whitespace into a single space. You can use the "non-breaking space" character instead. It may be written as "&nbs p;" in HTML (minus the space between s and p) or using its Unicode representation 00 A0. So your c# code becomes:
int len = dr["ACCT_GRP"].Length;
int paddingLength = 75 - len;
string padding = new string('\u00A0', paddingLength);

using c# how to Print Line number of randomly selected line from parsed file

this is a snippet of my program that catches an incomplete line in the file, however I need it to tell me the line number that it pulled so I can do error handling better.
var testLines = File.ReadAllLines(openFileDialog1.FileName);
Item.ran = new Random(Guid.NewGuid().GetHashCode());
var randomTestLine = testLines[Item.ran.Next(testLines.Length)];
if (randomTestLine.StartsWith("*"))
{
pick++;
count = pick.ToString();
Picks.Font = new Font("Microsoft Sans Serif", 12, FontStyle.Bold);
Picks.Text = count;
ItemGenerated.Text = ( !!something needs to go here!! + "Incomplete Item Entry\n" + randomTestLine);
return false;
}
var lineNumber = Item.ran.Next(testLines.Length);
var randomTestLine = testLines[lineNumber];
...
ItemGenerated.Text = ( lineNumber + "Incomplete Item Entry\n" + randomTestLine);
?

Old printer text format c#

I have the following output generated by an UNIX machine from 1996... We are upgrading the software for Windows, and I need to create this exact output http://pastebin.com/YBHpSYDW from C#
There are some problems I can't handle, because I don't know how...
How can I determinate the columns, set aligment for the "IMPORTE" column to the right, if it is plaintext?
I have done this output in Excel which is more readable, flexible.. but they want this creepy old stuff because a lot of reasons and they I'll become insane working for this people, they don't want to upgrade anything, just the software but keep every old creepy thing # output...
So if anyone knows a way to do this, it'll be so much helpful, thank you.
EDIT
The output is a list of data from an SQL Server, old data was stored into MultiValue .DAT and .IDX files, but now they're in a SQL Server... So basically, the code that generates the values is the following
var Query = getRows(sel.DataTable).Select(row =>
{
return new
{
banco = row["banco"].ToString(),
emisora = row["emisora"].ToString(),
sucursal = row["sucursal"].ToString(),
fecha = row["fecha"].ToString(),
identificacion = row["identificacion"].ToString(),
importe = row["importe"].ToString(),
importe_dec = row["importe_dec"].ToString(),
provincia = row["provincia"].ToString(),
referencia = row["referencia"].ToString(),
};
});
Then I do some foreach to make the magic... For example
foreach (var banco in Query.GroupBy(l => l.banco))
So the problem is the output file for printing...
EDIT 2
Got it working, here's the code
private void generarFicheroPrt()
{
try
{
SelectBD sel = new SelectBD(Program.ConexBD, "SELECT * FROM Seguros");
var Query = getRows(sel.DataTable).Select(row =>
{
return new
{
banco = row["banco"].ToString(),
emisora = row["emisora"].ToString(),
sucursal = row["sucursal"].ToString(),
fecha = row["fecha"].ToString(),
identificacion = row["identificacion"].ToString(),
importe = row["importe"].ToString(),
importe_dec = row["importe_dec"].ToString(),
provincia = row["provincia"].ToString(),
referencia = row["referencia"].ToString(),
};
});
using (StreamWriter sw = new StreamWriter(Program.path + #"\CV9005.prt"))
{
int i = 1;
int pag = 0;
int linea = 1;
sw.WriteLine();
sw.WriteLine("\x1b&l1O\x1b(s14H");
decimal total = 0;
foreach (var valor in Query.OrderBy(l => l.emisora))
{
if (linea == 48) linea = 1;
if (linea == 1)
{
pag++;
sw.WriteLine("\xc\t0125 BANCOFAR" + string.Empty.PadLeft(37, '\x20') + "COBRO POR VENTANILLA S. S. - CONTROL DE DOCUMENTOS PAG. "+ pag +"\n\n");
sw.WriteLine("\t N.ORDEN NUMERO REFERENCIA IMPORTE SUC. EMISORA");
sw.WriteLine("\t ------- ----------------- ---------------- ---- -----------------------------------------------------------");
sw.WriteLine();
}
setSufijoEmisora(valor.emisora);
decimal importe = Convert.ToDecimal(Int32.Parse(valor.importe) + "," + valor.importe_dec);
string imp = importe.ToString("N2", Cultures.Spain);
sw.WriteLine("\t\t" + string.Format("{0, 4}\t{1, -13}\t\t{2, 13}{3,6} {4, -59}", i.ToString(), valor.referencia, imp, valor.sucursal, valor.emisora + " " + sufijoEmisora));
i++;
linea++;
total = total + importe;
}
sw.WriteLine();
sw.WriteLine("\t\t\t\t\t TOTAL .....\t" + string.Format("{0, 13}", total.ToString("N2", Cultures.Spain)));
};
}
catch (Exception ex)
{
Logger.log(ex);
}
}
Use the "PrintDocument" tool from the toolbox.
http://msdn.microsoft.com/en-gb/library/system.drawing.printing.printdocument%28v=vs.110%29.aspx
This will help you with basic formating.
Edit
For more richer formating and saving to file use the Microsoft.Office.Core namespace,
http://msdn.microsoft.com/en-us/library/microsoft.office.core.aspx
If you want non ASCII encoding, make sure to set the encoding as per your requirement and save the file with the required encoding.
http://msdn.microsoft.com/en-us/library/microsoft.office.core.msoencoding.aspx
using(StreamWriter writer = new StreamWriter("a.txt", false, Encoding.UTF8))
{
writer.WriteLine(s);
}

Categories

Resources