i am trying to generate a pdf file using itextsharp in asp.net c#.
I came across table concept in itextsharp n i am trying to use it ie my application. I am having the following problem while using tables.
The pdf cell which contains Name of treasery the word treasery comes on next line. I am setting width for each cell. if i increase the width than also no changes come. The gap which is shown using arrow in below image remain as it is al the time. Why is that gap?How to remove that gap?
I want a dotted line as a border to only one cell. how to do that?here is my code
PdfPTable line6table = new PdfPTable (3);
float[] width = new float[] { 2.5F, 1.5F, 3.0F };
line6table.SetWidths(width);
line6table.HorizontalAlignment = 0;
line6table.WidthPercentage = 100.0f;
line6table.SpacingBefore = 6.0f;
PdfPCell a1 = new PdfPCell(new Phrase("Head Of Account"));
a1.Border = 1;
a1.Indent = 2.2f;
a1.PaddingTop = 5.0f;
line6table.AddCell(a1);
PdfPCell a2 = new PdfPCell(new Phrase("CHARGED"));
a2.Border = 1;
a2.PaddingTop = 5.0f;
line6table.AddCell(a2);
PdfPCell a3 = new PdfPCell(new Phrase("Name of the treasry"));
a3.Border = 0;
a3.Indent = 15.0f;
a3.RightIndent = 0.0f;
a3.HorizontalAlignment = 1;
line6table.AddCell(a3);
pdfDocument.Add(line6table);
Please help me to resolve my problem.
line6table.WidthPercentage = 100.0f;
This did it for me.
Increase the width of the column.
Related
I have used iTextSharp to generate a PDF file.
I have created 6 PdfPTables but it shows only 3.
// Create new PDF document
Document document = new Document(PageSize.A4, 20f, 20f, 20f, 20f);
try {
PdfWriter writer = PdfWriter.GetInstance(document,
new FileStream(filename, FileMode.Create));
document.Open();
int spacing = 0;
for (int i = 0; i <= 6; i++) {
PdfPTable table = new PdfPTable(2);
table.TotalWidth = 144f;
table.LockedWidth = false;
PdfPCell cell = new PdfPCell(new Phrase("This is table" + i));
cell.Colspan = 3;
cell.HorizontalAlignment = 1;
table.AddCell(cell);
table.WriteSelectedRows(0, -1,
document.Left + spacing, document.Top,
writer.DirectContent);
spacing = spacing + 200;
}
}
catch (Exception ex) {}
finally {
document.Close();
ShowPdf(filename);
}
Here I have put the for loop for 6 times but it shows only 3 table.
How can I show all 6 tables? I want to show only 3 table in 1 line after that break to new line and display other 3 tables.
I think the title of your question pretty much sums up the problem actually.
When you use WriteSelectedRows it is your responsibility to provide the X and Y locations to write to and you are drawing outside of the page boundaries. A4 has 595 horizontal units and there's just not enough room. This is 100% valid however most people won't see it. I'm guessing that you want to "wrap" your table to the next line. There's a couple of ways of doing that:
Bigger page size
Switch to something like PageSize.A0 and you should have more room. The page size is just a hint, anyway, print software will scale as needed.
MOD check in loop
This is the little more complicated one but every n tables you reset the x coordinate to the left edge and increase your y by the tallest of the previous row of tables.
int spacing = 0;
//The current Y position
float curY = document.Top;
//Well ask iText how tall each table was and set the tallest to this variable
float lineHeight = 0;
//Maximum number of tables that go on a line
const int maxPerLine = 3;
for (int i = 0; i <= 6; i++) {
PdfPTable table = new PdfPTable(2);
table.TotalWidth = 144f;
table.LockedWidth = false;
PdfPCell cell = new PdfPCell(new Phrase("This is table" + i));
cell.Colspan = 3;
cell.HorizontalAlignment = 1;
table.AddCell(cell);
table.WriteSelectedRows(0, -1,
document.Left + spacing, curY,
writer.DirectContent);
spacing = spacing + 200;
//Set the height to whichever is taller, the last table or this table
lineHeight = Math.Max(lineHeight, table.TotalHeight);
//If we're at the "last" spot in the "row"
if (0 == (i + 1) % maxPerLine) {
//Offset our Y by the tallest table
curY -= lineHeight;
//Reset "row level" variables
spacing = 0;
lineHeight = 0;
}
}
Wrapper table
This is what I really recommend. If you want to "wrap" tables then just use an outer table to hold your inner tables and you get everything for free and you don't have to mess with DirectContent (although you'll probably want to change table borders).
var outerTable = new PdfPTable(3);
outerTable.DefaultCell.Border = PdfPCell.NO_BORDER;
for (int i = 0; i <= 6; i++) {
PdfPTable innerTable = new PdfPTable(2);
innerTable.TotalWidth = 144f;
innerTable.LockedWidth = false;
PdfPCell cell = new PdfPCell(new Phrase("This is table" + i));
cell.Colspan = 3;
cell.HorizontalAlignment = 1;
innerTable.AddCell(cell);
outerTable.AddCell(innerTable);
}
document.Add(outerTable);
I'am creating a 2*2 table on pdf file. I Just want to put outer border for the table, No need to show the inner cells border. I have tried like this
var back= new PdfPTable(2); //table for back
back.DefaultCell.Border = 1;
PdfPCell cell20 = new PdfPCell(new Phrase("cell1", body));
cell20.Border = 0;
back.AddCell(cell20);
PdfPCell cell21 = new PdfPCell(new Phrase("cell2", body));
cell21.Border = 0;
cell21.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
back.AddCell(cell21);
PdfPCell cell22 = new PdfPCell(new Phrase("cell3"));
cell22.Border = 0;
cell22.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
back.AddCell(cell22);
PdfPCell cell23 = new PdfPCell(new Phrase("cell4", body));
cell23.Border = 0;
cell23.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
back.AddCell(cell23);
but it results a table without any border, please help
You need to create a table event, for instance:
public class OuterBorder implements PdfPTableEvent {
public void tableLayout(PdfPTable table, float[][] width, float[] height,
int headerRows, int rowStart, PdfContentByte[] canvas) {
float widths[] = width[0];
float x1 = widths[0];
float x2 = widths[widths.length - 1];
float y1 = height[0];
float y2 = height[height.length - 1];
PdfContentByte cb = canvas[PdfPTable.LINECANVAS];
cb.rectangle(x1, y1, x2 - x1, y2 - y1);
cb.stroke();
}
}
As you can see, we use the width and height parameter passed to the tableLayout() method to define the borders of a rectangle, and we draw that rectangle to the LINECANVAS.
For this table event to work, you need to declare it to the table. In your case, that would be:
back.setTableEvent(new OuterBorder());
Note that my code is written in Java based on the PressPreviews example from my book. For the corresponding C# code, please consult the iTextSharp examples.
I am using itext sharp for creating reports in PDF format.
I want page borders. I tried some ways. I am not successful.
How can I get a page border for top, bottom, left, right using iText for .NET?
I added one image 1. I want borders like described in the image.
You can try this code for adding the image for the header manually.
//Step 1: Add the Image file
strImgPath is refer the directory Info..
Image imgLogo = Image.GetInstance(strImgPath.ToString()+"\\abcdur compe.Jpg");
imgLogo.Alignment = Image.ALIGN_CENTER;
imgLogo.ScalePercent(50f);
// Step 2:
Add this ImgLogo to the PdfPTable by use of this
PdfPCell pdfcellImage = new PdfPCell(imgLogo, true);
pdfcellImage.FixedHeight = 40f;
pdfcellImage.HorizontalAlignment = Element.ALIGN_CENTER;
pdfcellImage.VerticalAlignment = Element.ALIGN_CENTER;
pdfcellImage.Border = Rectangle.NO_BORDER;
pdfcellImage.Border = Rectangle.NO_BORDER;
pdftblImage.AddCell(pdfcellImage);
// Step 3:
Create Chunck to add Text for address or others
fntBoldComHd is a Base Font Library Object
Chunk chnCompany = new Chunk("Your CompanyName\nAddress", fntBoldComHd);
//Step 4:
Create Phrase For add the Chunks and PdfPTables
Phrase phHeader = new Phrase();
phHeader.Add(pdftblImage);
phHeader.Add(chnCompany);
// Step 5:
Assign the Phrase to PDF Header
HeaderFooter header = new HeaderFooter(phHeader, false);
header.Border = Rectangle.NO_BORDER;
header.Alignment = Element.ALIGN_CENTER;
docPDF.Header = header;
I am using one hacky way of workaround but it will create the border.Use this method.
private void CreateBorder(PdfContentByte cb, PdfWriter writer, Document doc)
{
iTextSharp.text.Rectangle r = doc.PageSize;
float left = r.Left + 30;
float right = r.Right - 30;
float top = r.Top - 30;
float bottom = r.Bottom + 30;
float width = right - left;
float height = top - bottom;
PdfPTable tab = new PdfPTable(1);
tab.TotalWidth = width;
tab.LockedWidth = true;
PdfPCell t = new PdfPCell(new Phrase(String.Empty));
t.BackgroundColor = new BaseColor(250, 235, 215);
t.FixedHeight = height;
t.BorderWidth = 3;
tab.AddCell(t);
Paragraph pa = new Paragraph();
pa.Add(tab);
float h = tab.TotalHeight;
PdfTemplate temp = cb.CreateTemplate(tab.TotalWidth, h);
tab.WriteSelectedRows(0, -1, 0.0F, h, temp);
iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(temp);
img.SetAbsolutePosition(30, 30);
cb.AddImage(img);
}
If u want one more section for header create table width two rows.I hope this helps.
Are you referring to the document margins? If yes, use the Document object's ctor to specify them:
public Document(Rectangle pageSize, float marginLeft, float marginRight, float marginTop, float marginBottom);
I have a C# application that generates a PDF invoice. In this invoice is a table of items and prices. This is generated using a PdfPTable and PdfPCells.
I want to be able to right-align the price column but I cannot seem to be able to - the text always comes out left-aligned in the cell.
Here is my code for creating the table:
PdfPTable table = new PdfPTable(2);
table.TotalWidth = invoice.PageSize.Width;
float[] widths = { invoice.PageSize.Width - 70f, 70f };
table.SetWidths(widths);
table.AddCell(new Phrase("Item Name", tableHeadFont));
table.AddCell(new Phrase("Price", tableHeadFont));
SqlCommand cmdItems = new SqlCommand("SELECT...", con);
using (SqlDataReader rdrItems = cmdItems.ExecuteReader())
{
while (rdrItems.Read())
{
table.AddCell(new Phrase(rdrItems["itemName"].ToString(), tableFont));
double price = Convert.ToDouble(rdrItems["price"]);
PdfPCell pcell = new PdfPCell();
pcell.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
pcell.AddElement(new Phrase(price.ToString("0.00"), tableFont));
table.AddCell(pcell);
}
}
Can anyone help?
I'm the original developer of iText, and the problem you're experiencing is explained in my book.
You're mixing text mode and composite mode.
In text mode, you create the PdfPCell with a Phrase as the parameter of the constructor, and you define the alignment at the level of the cell. However, you're working in composite mode. This mode is triggered as soon as you use the addElement() method. In composite mode, the alignment defined at the level of the cell is ignored (which explains your problem). Instead, the alignment of the separate elements is used.
How to solve your problem?
Either work in text mode by adding your Phrase to the cell in a different way.
Or work in composite mode and use a Paragraph for which you define the alignment.
The advantage of composite mode over text mode is that different paragraphs in the same cell can have different alignments, whereas you can only have one alignment in text mode. Another advantage is that you can add more than just text: you can also add images, lists, tables,... An advantage of text mode is speed: it takes less processing time to deal with the content of a cell.
private static PdfPCell PhraseCell(Phrase phrase, int align)
{
PdfPCell cell = new PdfPCell(phrase);
cell.BorderColor = BaseColor.WHITE;
// cell.VerticalAlignment = PdfCell.ALIGN_TOP;
//cell.VerticalAlignment = align;
cell.HorizontalAlignment = align;
cell.PaddingBottom = 2f;
cell.PaddingTop = 0f;
return cell;
}
Here is my derivation of user2660112's answer - one method to return a cell for insertion into a bordered and background-colored table, and a similar, but borderless/colorless variety:
private static PdfPCell GetCellForBorderedTable(Phrase phrase, int align, BaseColor color)
{
PdfPCell cell = new PdfPCell(phrase);
cell.HorizontalAlignment = align;
cell.PaddingBottom = 2f;
cell.PaddingTop = 0f;
cell.BackgroundColor = color;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
return cell;
}
private static PdfPCell GetCellForBorderlessTable(Phrase phrase, int align)
{
PdfPCell cell = new PdfPCell(phrase);
cell.HorizontalAlignment = align;
cell.PaddingBottom = 2f;
cell.PaddingTop = 0f;
cell.BorderWidth = PdfPCell.NO_BORDER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
return cell;
}
These can then be called like so:
Font timesRoman9Font = FontFactory.GetFont(FontFactory.TIMES_ROMAN, 9, BaseColor.BLACK);
Font timesRoman9BoldFont = FontFactory.GetFont(FontFactory.TIMES_BOLD, 9, BaseColor.BLACK);
Phrase phrasesec1Heading = new Phrase("Duckbills Unlimited", timesRoman9BoldFont);
PdfPCell cellSec1Heading = GetCellForBorderedTable(phrasesec1Heading, Element.ALIGN_LEFT, BaseColor.YELLOW);
tblHeadings.AddCell(cellSec1Heading);
Phrase phrasePoisonToe = new Phrase("Poison Toe Toxicity Level (Metric Richter Scale, adjusted for follicle hue)", timesRoman9Font);
PdfPCell cellPoisonToe = GetCellForBorderlessTable(phrasePoisonToe, Element.ALIGN_LEFT);
tblFirstRow.AddCell(cellPoisonToe);
I ended up here searching for java Right aligning text in PdfPCell. So no offense if you are using java please use given snippet to achieve right alignment.
private PdfPCell getParagraphWithRightAlignCell(Paragraph paragraph) {
PdfPCell cell = new PdfPCell(paragraph);
cell.setBorderColor( BaseColor.WHITE);
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
return cell;
}
In getParagraphWithRightAlignCell pass paragraph
Thanks
Perhaps its because you are mixing the different ways to add the cells? Have you tried explicitly creating a cell object, massaging it however you want then adding it for every cell?
Another thing you could try is setting the vertical alignment as well as the horizontal.
cell.HorizontalAlignment = Element.ALIGN_RIGHT;
I want to create a PDF file with Icard showing in it.
Following is the code:
iTextSharp.text.Font custFont = new iTextSharp.text.Font() { Size=6f};
int borderSize = 1;
Document IcardDoc = new Document(PageSize.HALFLETTER);
PdfWriter.GetInstance(IcardDoc, Response.OutputStream);
IcardDoc.Open();
PdfPTable icardTable = new PdfPTable(2);
iTextSharp.text.Image logoImage = iTextSharp.text.Image.GetInstance(Server.MapPath("~/images/logo.jpg"));
logoImage.WidthPercentage = 15f;
PdfPCell cell = new PdfPCell(logoImage, false);
cell.PaddingLeft = 10f;
cell.PaddingTop = 10f;
cell.PaddingBottom = 10f;
cell.PaddingRight = 10f;
cell.Colspan = 2;
cell.Border = 0;
cell.HorizontalAlignment = 1;
icardTable.AddCell(cell);
icardTable.AddCell(new PdfPCell(new Phrase("Name:", custFont)) { Border = borderSize });
icardTable.AddCell(new PdfPCell(new Phrase(student.firstname + " " + student.lastname, custFont)) { Border = borderSize });
The print document size will be 8.5 cm in height and 5.4 cm in width.
So need to fit it that way, is there any solution to this because the above code is not fitting the table on page and in proper size?
Any other format will also do like word etc.
figured out the solution :
Document IcardDoc = new Document(new Retangele(200f, 315f),35f,35f,0f,0f);
and adjust the width of the table accordingly:
PdfPTable icardTable = new PdfPTable(2);
icardTable.WidthPercentage = 140f;
to fit table exactly on page, if decrease rectangle width then increase table WidthPercentage and vice versa.
You also need to care of left and right margins defined as 35f in Document class constructor
This worked for me.
var pgSize = new iTextSharp.text.Rectangle(1042, 651);
var doc = new iTextSharp.text.Document(pgSize, 0, 0, 0, 0);