How to put table in proper way with itextpdf in android? - sqlite

I want to export my Sqlite to a PDF. I am able to do it but instead of putting the result in just one row, it puts the the result in the other column i have. What I want is to fill the row in the same column(incremente the rows)with the database results. This is what I have, Can you help me with this?
db = new Database(FirstActivity.this);
Cursor c = bd.getGroupsNamesMachines();
PdfPTable table = new PdfPTable(2);
cell = new PdfPCell(new Phrase("groups"));
cell2 = new PdfPCell(new Phrase("machines"));
if (c.moveToFirst()) {
do {
String groups = c.getString(c.getColumnIndex("groupname"));
cell3 = new PdfPCell(new Phrase(groups));
table.addCell(cell3);
} while (c.moveToNext());
}
cell.setColspan(1);
cell2.setColspan(2);
cell3.setColspan(1);
table.addCell(cell);
table.addCell(cell2);
table.addCell(cell3);

Please read the documentation, or watch this video (before the first 10 minutes are over, you'll know how to create a table that shows all the states of the US). The code for that example can be found here: set format of header row using iText
In your case, you are doing something really strange. You create a table with 2 columns. That's OK if each record has two fields. However, you add the body cells before you add the header cells. I think you're trying to create a header row with 3 columns (which is illogical), and you probably don't complete the last row (and iText only adds complete rows by default).
You need something like this:
// Table
PdfPTable table = new PdfPTable(2);
// Header
PdfPCell cell1 = new PdfPCell(new Phrase("groups"));
PdfPCell cell2 = new PdfPCell(new Phrase("machines"));
table.addCell(cell1);
table.addCell(cell2);
// Data
db = new Database(FirstActivity.this);
Cursor c = db.getGroupsNamesMachines();
if (c.moveToFirst()) {
do {
String group = c.getString(c.getColumnIndex("groupname"));
cell1 = new PdfPCell(new Phrase(group));
table.addCell(cell1);
String machine = c.getString(c.getColumnIndex("machinename"));
cell2 = new PdfPCell(new Phrase(machine));
table.addCell(cell2);
} while (c.moveToNext());
}
document.add(table);
I don't know if the database code is OK; it's your responsibility to know how to get the correct data from the database, but please compare your very asymmetric code with the logical code I changed it into.
First define the header, and add it to the table,
Then loop over the data, and add the data row by row,
Never add more cells to a row than there are columns!

Related

Giving zero indent for inner cell Indent in Aspose Word

I am trying to create inner cells in pdf with using aspose words. But I have issues about its style. I need to center and fit my text in cell. But when I set center property for cell it gives some padding automatically.
I made a sample with MS word as below image:
This one is that I have created programmatically with using aspose words.
As you can see it doesn't fit when I set center property true for columns.
My inner cell import code is below:
Cell cell = table.Rows[j].Cells[i];
cell.CellFormat.RightPadding = 0;
foreach (Paragraph pf in cell.Paragraphs)
{
pf.ParagraphFormat.LeftIndent = 0;
}
cell.CellFormat.WrapText = false;
builder.MoveTo(cell.FirstParagraph);
builder.InsertCell();
builder.Writeln(tr.Rows[j][i].Value);
builder.EndTable();
Which property should I set to fit it in cell, thanks.
Please use following code example to get the required output. You may modify the table/cell width according to your requirement. I suggest you please read following link to work with tables. Hope this helps you.
Working with Tables
If you still face problem, share your input and expected output documents. I will share the code according to your expected document.
Document doc = new Document();
DocumentBuilder builder = new DocumentBuilder(doc);
builder.Font.Name = "Calibri";
builder.CellFormat.LeftPadding = 0;
builder.CellFormat.RightPadding = 0;
builder.CellFormat.TopPadding = 0;
builder.CellFormat.BottomPadding = 0;
Table table = builder.StartTable();
// Insert a cell
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(33);
//Insert inner table
Table table1 = builder.StartTable();
builder.InsertCell();
table1.Alignment = TableAlignment.Left;
table1.PreferredWidth = PreferredWidth.FromPercent(50);
builder.Write("This is cell 1");
builder.EndRow();
builder.EndTable();
// Insert a cell
builder.InsertCell();
//Insert inner table
Table table2 = builder.StartTable();
builder.InsertCell();
table2.Alignment = TableAlignment.Center;
table2.PreferredWidth = PreferredWidth.FromPercent(50);
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center;
builder.Write("This is cell 2");
builder.EndRow();
builder.EndTable();
// Insert a cell
builder.InsertCell();
builder.CellFormat.PreferredWidth = PreferredWidth.FromPercent(33);
//Insert inner table
Table table3 = builder.StartTable();
builder.InsertCell();
table3.PreferredWidth = PreferredWidth.FromPercent(50);
table3.Alignment = TableAlignment.Right;
builder.ParagraphFormat.Alignment = ParagraphAlignment.Right;
builder.Write("This is cell 3");
builder.EndRow();
builder.EndTable();
builder.EndRow();
builder.EndTable();
doc.Save(MyDir + "Out.docx");
I work with Aspose as Developer evangelist.

Asp.net itextsharp issue with row's text close to bottomline

I am working on generating pdf using itextsharp ,In my table i have multiple columns such as sr.ni. name .],quantity ,mrp ,price tax etc.
Name column has round about 40% of total width all values in other column comes right in middle of row but name's value is somehow close to bottom line ,Everything is same for all columns ie. style,font etc.
code
var cell=new PdfPcell();
cell = new PdfPCell(new Phrase(price, font));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.VerticleAlignMent= Element.ALIGN_CENTER;
producttable.AddCell(cell);
same code for all values
any solutions.
also tried
cell.AddElement(new Chunk(name, font));
cell.HorizontalAlignment = Element.ALIGN_LEFT;
cell.VerticalAlignment = Element.ALIGN_MIDDLE;
productsTable.AddCell(cell);
didnt work
You can assign vertical alignment to your particular cell as shown below:
pdfCell2.VerticalAlignment = Element.ALIGN_BOTTOM;
pdfCell3.VerticalAlignment = Element.ALIGN_MIDDLE;
pdfCell4.VerticalAlignment = Element.ALIGN_TOP;

How to add an image to a table cell in iTextSharp using webmatrix

I have made a table with cells and interested in having an image in one of the cell.
Below is my code:
doc.Open();
PdfPTable table = new PdfPTable(2);
table.TotalWidth = 570f;
table.LockedWidth = true;
table.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
PdfPCell points = new PdfPCell(new Phrase("and is therefore entitled to 2 points", arialCertify));
points.Colspan = 2;
points.Border = 0;
points.PaddingTop = 40f;
points.HorizontalAlignment = 1;//0=Left, 1=Centre, 2=Right
table.AddCell(points);
// add a image
doc.Add(table);
Image jpg = Image.GetInstance(imagepath + "/logo.jpg");
doc.Add(jpg);
With the above code, the image shows in my pdf but I want it to be inside a cell so that I can add more cells to the right of the image.
On the very basic level you can simply add the image to a PdfPCell and add this cell to your table.
So using your code...
PdfPCell points = new PdfPCell(new Phrase("and is therefore entitled to 2 points", arialCertify));
points.Colspan = 2;
points.Border = 0;
points.PaddingTop = 40f;
points.HorizontalAlignment = 1;//0=Left, 1=Centre, 2=Right
// add a image
iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imagepath + "/logo.jpg");
PdfPCell imageCell = new PdfPCell(jpg);
imageCell.Colspan = 2; // either 1 if you need to insert one cell
imageCell.Border = 0;
imageCell.setHorizontalAlignment(Element.ALIGN_CENTER);
table.AddCell(points);
// add a image
table.AddCell(imageCell);
doc.Add(table);
Update
Check your imagepath. This should be an absolute path to the image, and not relative like in a website page. Also, change your `/logo.jpg' to '\logo.jpg'
this is assuming imagepath is actually to the directory, and not the actual image...
I.E
Server.MapPath(imagepath) + "\\logo.jpg"

bulk insertion in MS SQL from a text file

I have a text file that contains around 21 lac entries and I want to insert all these entries into a table. Initially I have created one function in c# that read line by line and insert into table but it takes too much time. Please suggest an efficient way to insert these bulk data and that file is containing TAB(4 spaces) as delimiter.
And that text file also containing some duplicate entries and I don't want to insert those entries.
Load all of your data into a DataTable object and then use SqlBulkCopy to bulk insert them:
DataTable dtData = new DataTable("Data");
// load your data here
using (SqlConnection dbConn = new SqlConnection("db conn string"))
{
dbConn.Open();
using (SqlTransaction dbTrans = dbConn.BeginTransaction())
{
try
{
using (SqlBulkCopy dbBulkCopy = new SqlBulkCopy(dbConn, SqlBulkCopyOptions.Default, dbTrans))
{
dbBulkCopy.DestinationTableName = "intended SQL table name";
dbBulkCopy.WriteToServer(dtData );
}
dbTrans.Commit();
}
catch
{
dbTrans.Rollback();
throw;
}
}
dbConn.Close();
}
I've included the example to wrap this into a SqlTransaction so there will be a full rollback if there's a failure along the way. To get you started, here's a good CodeProject article on loading the delimited data into a DataSet object.
Sanitizing the data before loading
OK, here's how I think your data looks:
CC_FIPS FULL_NAME_ND
AN Xixerella
AN Vila
AN Sornas
AN Soldeu
AN Sispony
... (cut down for brevity)
In this instance you want to create your DataTable like this:
DataTable dtData = new DataTable("Data");
dtData.Columns.Add("CC_FIPS");
dtData.Columns.Add("FULL_NAME_ND");
Then you want to iterate each row (assuming your tab delimited data is separated row-by-row by carriage returns) and check whether this data already exists in the DataTable using the .Select method and if there is a match (i'm checking for BOTH values, it's up to you whether you want to do something else) then don't add it thereby preventing duplicates.
using (FileStream fs = new FileStream("path to your file", FileMode.Open, FileAccess.Read))
{
int rowIndex = 0;
using (StreamReader sr = new StreamReader(fs))
{
string line = string.Empty;
while (!sr.EndOfStream)
{
line = sr.ReadLine();
// use a row index to skip the header row as you don't want to insert CC_FIPS and FULL_NAME_ND
if (rowIndex > 0)
{
// split your data up into a 2-d array tab delimited
string[] parts = line.Split('\t');
// now check whether this data has already been added to the datatable
DataRow[] rows = dtData.Select("CC_FIPS = '" + parts[0] + "' and FULL_NAME_ND = '" + parts[1] + "'");
if (rows.Length == 0)
{
// if there're no rows, then the data doesn't exist so add it
DataRow nr = dtData.NewRow();
nr["CC_FIPS"] = parts[0];
nr["FULL_NAME_ND"] = parts[1];
dtData.Rows.Add(nr);
}
}
rowIndex++;
}
}
}
At the end of this you should have a sanitized DataTable that you can bulk insert. Please note that this code isn't tested, but it's a best guess as to how you should do it. There are many ways this can be done, and probably a lot better than this method (specifically LINQ) - but it's a starting point.

Retrieve Cellset Value in SSAS\MDX

Im writing SSAS MDX queries involving more than 2 axis' to retrieve a value. Using ADOMD.NET, I can get the returned cellset and determine the value by using
lblTotalGrossSales.Text = CellSet.Cells(0).Value
Is there a way I can get the CellSet's Cell(0) Value in my MDX query, instead of relying on the data returning to ADOMD.NET?
thanks!
Edit 1: - Based on Daryl's comment, here's some elaboration on what Im doing. My current query is using several axis', which is:
SELECT {[Term Date].[Date Calcs].[MTD]} ON 0,
{[Sale Date].[YQMD].[DAY].&[20121115]} ON 1,
{[Customer].[ID].[All].[A612Q4-35]} ON 2,
{[Measures].[Loss]} ON 3
FROM OUR_CUBE
If I run that query in Management Studio, I am told Results cannot be displayed for cellsets with more than two axes - which makes sense since.. you know.. there's more than 2 axes. However, if I use ADOMD.NET to run this query in-line, and read the returning value into an ADOMD.NET cellset, I can check the value at cell "0", giving me my value... which as I understand it (im a total noob at cubes) is the value sitting where all these values intersect.
So to answer your question Daryl, what I'd love to have is the ability to have the value here returned to me, not have to read in a cell set into the calling application. Why you may ask? Well.. ultimately I'd love to have one query that performs several multi-axis queries to return the values. Again.. Im VERY new to cubes and MDX, so it's possible Im going at this all wrong (Im a .NET developer by trade).
Simplify your query to return two axis;
SELECT {[Measures].[Loss]} ON 0, {[Term Date].[Date Calcs].[MTD] * [Sale Date].[YQMD].[DAY].&[20121115] * [Customer].[ID].[All].[A612Q4-35]} ON 1 FROM OUR_CUBE
and then try the following to access the cellset;
string connectionString = "Data Source=localhost;Catalog=AdventureWorksDW2012";
//Create a new string builder to store the results
System.Text.StringBuilder result = new System.Text.StringBuilder();
AdomdConnection conn = new AdomdConnection(connectionString);
//Connect to the local serverusing (AdomdConnection conn = new AdomdConnection("Data Source=localhost;"))
{
conn.Open();
//Create a command, using this connection
AdomdCommand cmd = conn.CreateCommand();
cmd.CommandText = #"SELECT { [Measures].[Unit Price] } ON COLUMNS , {[Product].[Color].[Color].MEMBERS-[Product].[Color].[]} * [Product].[Model Name].[Model Name]ON ROWS FROM [Adventure Works] ;";
//Execute the query, returning a cellset
CellSet cs = cmd.ExecuteCellSet();
//Output the column captions from the first axis//Note that this procedure assumes a single member exists per column.
result.Append("\t\t\t");
TupleCollection tuplesOnColumns = cs.Axes[0].Set.Tuples;
foreach (Microsoft.AnalysisServices.AdomdClient.Tuple column in tuplesOnColumns)
{
result.Append(column.Members[0].Caption + "\t");
}
result.AppendLine();
//Output the row captions from the second axis and cell data//Note that this procedure assumes a two-dimensional cellset
TupleCollection tuplesOnRows = cs.Axes[1].Set.Tuples;
for (int row = 0; row < tuplesOnRows.Count; row++)
{
for (int members = 0; members < tuplesOnRows[row].Members.Count; members++ )
{
result.Append(tuplesOnRows[row].Members[members].Caption + "\t");
}
for (int col = 0; col < tuplesOnColumns.Count; col++)
{
result.Append(cs.Cells[col, row].FormattedValue + "\t");
}
result.AppendLine();
}
conn.Close();
TextBox1.Text = result.ToString();
} // using connection
Source : Retrieving Data Using the CellSet
This is fine upto select on columns and on Rows. It will be helpful analyze how to traverse sub select queries from main query.

Resources