image displays size issue [duplicate] - c#

This question already has answers here:
How to resize an iTextSharp.text.Image size into my code?
(3 answers)
Closed 8 years ago.
I am trying to display some images in pdf using iTextSharp.Its working fine but my problem is, some images displays in zooming from its actual size like below image,
The code I tried to display is,
iTextSharp.text.Font fontH1 = new iTextSharp.text.Font(Currier, 18, iTextSharp.text.Font.BOLD);
Document doc1 = new Document();
string path1 = Environment.GetFolderPath(Environment.SpecialFolder.CommonDocuments);
path1 = path1 + "\\DOC\\Mathematicsquestions.pdf";
iTextSharp.text.Rectangle pageSize1 = doc1.PageSize;
PdfWriter pdf = PdfWriter.GetInstance(doc1, new FileStream(path1, FileMode.Create));
doc1.Open();
pdf.Open();
PdfPTable table = new PdfPTable(2);
//actual width of table in points
table.TotalWidth = 500f;
//fix the absolute width of the table
table.LockedWidth = true;
//relative col widths in proportions - 1/3 and 2/3
float[] widths = new float[] { 0.15f, 2.5f };
table.SetWidths(widths);
table.HorizontalAlignment = 0;
//leave a gap before and after the table
table.SpacingBefore = 0f;
table.SpacingAfter = 0f;
PdfPCell cell = new PdfPCell(new Phrase("MATHEMATICS", fontH1));
cell.Colspan = 2;
cell.Border = 0;
cell.HorizontalAlignment = 1;
table.AddCell(cell);
PdfPCell cell1 = new PdfPCell(new Phrase(" "));
cell1.Colspan = 2;
cell1.Border = 0;
cell1.HorizontalAlignment = 1;
table.AddCell(cell1);
for (int i = 0; i < mach.Count; i++)
{
string temsub = mach[i].ToString();
var quepaper1 = from fm in en.Entrance_jee where fm.En_Chapter == temsub select fm;
foreach (Entrance_jee re in quepaper1)
{
if (newsno == 0)
{
newsno = 1;
}
else
{
newsno = newsno + 1;
}
if (re.En_Isimage == true)
{
imgepath = path + re.En_Questionpage1 + ".png";
imgepath2 = path + re.En_Answer + ".png";
filename = System.IO.Path.GetFileName(imgepath);
filename2 = System.IO.Path.GetFileName(imgepath2);
decfile = decfile1 + "\\R1\\CF\\" + filename;
decfile2 = decfile1 + "\\R1\\CF\\" + filename2;
string status = encobj.DecryptFile(imgepath, decfile);
status = encobj.DecryptFile(imgepath2, decfile2);
if (status == "decrypted")
{
byte[] file = File.ReadAllBytes(decfile);
File.Delete(decfile);
iTextSharp.text.Image img1 = iTextSharp.text.Image.GetInstance(file);
byte[] file2 = File.ReadAllBytes(decfile2);
File.Delete(decfile2);
iTextSharp.text.Image img2 = iTextSharp.text.Image.GetInstance(file2);
//iTextSharp.text.pdf.PdfPCell imgCell1 = new iTextSharp.text.pdf.PdfPCell();
//imgCell1.AddElement(new Chunk(img2, 0, 0));
table.AddCell(newsno.ToString());
table.AddCell(img1);
table.AddCell(" ");
table.AddCell(img2);
}
}
else
{
table.AddCell(newsno.ToString());
table.AddCell(re.En_Questionpage1.ToString());
table.AddCell(" ");
table.AddCell(re.En_Answer.ToString());
}
}
}
doc1.Add(table);
doc1.Close();
Updated : Here is my orginal images,
Someone tell me where I am wrong?

The image appears to be scaled to the full width of the table. You need to scale it to your exact size requirements.
Try something like
iTextSharp.text.Image img1 = iTextSharp.text.Image.GetInstance(file);
iTextSharp.text.Image img2 = iTextSharp.text.Image.GetInstance(file2);
img1.ScaleToFit(500f, 37f);
img2.ScaleToFit(81f, 36f);
Or alternatively you can add a container within the cell with the required dimensions and add the image to it. See full details on - http://www.mikesdotnetting.com/article/87/itextsharp-working-with-images

Related

Generate a PDF file from two gridviews using iTextSharp

I use to generate a PDF file from a gridview using iTextSharp.
I need a help because I am not familiar with iTextSharp.
I'm using two gridviews in my aspx page: gvProducts and gvUsers.
The generation a PDF file from a single (gvProducts) gridview using iTextSharp working correctly.
I can't print the first and second GridView in the same PDF.
This is what I want:
Open PDF document;
Print result of my first GridView;
Print result of my second GridView;
Close, Save and download PDF document in the client.
Anybody know how can I do that?
Thank you in advance.
My code below.
protected void ExportToPDFWithFormatting()
{
//link button column is excluded from the list
int colCount = gvProducts.Columns.Count - 1;
//Create a table
PdfPTable table = new PdfPTable(colCount);
table.HorizontalAlignment = 1;
table.WidthPercentage = 100;
//create an array to store column widths
int[] colWidths = new int[gvProducts.Columns.Count];
PdfPCell cell;
string cellText;
//create the header row
for (int colIndex = 0; colIndex < colCount; colIndex++)
{
table.SetWidths(new int[] { 0, 40, 120, 110, 60, 60, 100, 90, 100, 50, 50, 50, 40, 30, 260, 200, 0 });
//fetch the header text
cellText = Server.HtmlDecode(gvProducts.HeaderRow.Cells[colIndex].Text);
//create a new cell with header text
BaseFont bf = BaseFont.CreateFont(
BaseFont.HELVETICA,
BaseFont.CP1252,
BaseFont.EMBEDDED,
false);
iTextSharp.text.Font font = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.BOLD, BaseColor.WHITE);
cell = new PdfPCell(new Phrase(cellText.Replace("<br />", Environment.NewLine), font));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.VerticalAlignment = Element.ALIGN_MIDDLE;
cell.FixedHeight = 45f;
//set the background color for the header cell
cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#a52a2a"));
//add the cell to the table. we dont need to create a row and add cells to the row
//since we set the column count of the table to 4, it will automatically create row for
//every 4 cells
table.AddCell(cell);
}
//export rows from GridView to table
for (int rowIndex = 0; rowIndex < gvProducts.Rows.Count; rowIndex++)
{
if (gvProducts.Rows[rowIndex].RowType == DataControlRowType.DataRow)
{
for (int j = 0; j < gvProducts.Columns.Count - 1; j++)
{
//fetch the column value of the current row
cellText = Server.HtmlDecode(gvProducts.Rows[rowIndex].Cells[j].Text);
//create a new cell with column value
cell = new PdfPCell(new Phrase(cellText, FontFactory.GetFont("PrepareForExport", 8)));
cell.HorizontalAlignment = Element.ALIGN_CENTER;
cell.VerticalAlignment = Element.ALIGN_MIDDLE;
cell.FixedHeight = 25f;
//Set Color of Alternating row
if (rowIndex % 2 != 0)
{
cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#f5f5dc"));
}
else
{
cell.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#fcfcfc"));
}
//add the cell to the table
table.AddCell(cell);
}
}
}
//Create the PDF Document
Document pdfDoc = new Document(PageSize.A3.Rotate(), 30f, 30f, 30f, 0f);
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
//open the stream
pdfDoc.Open();
table.HeaderRows = 1;
iTextSharp.text.Font fdefault = FontFactory.GetFont("Verdana", 18, iTextSharp.text.Font.BOLD, BaseColor.BLUE);
string s = "Report";
pdfDoc.Add(new Paragraph(s, fdefault));
//add the table to the document
pdfDoc.Add(table);
//close the document stream
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;" + DateTime.Now + ".pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
}
Edit #1
This is my code for generate pdf on GridView number two (gvUsers).
The code working but in the headers columns I have the names of GridView number one (gvProducts)... why?
//start pdf gridview number two
int colCountUsers = gvUsers.Columns.Count - 1;
PdfPTable tableUsers = new PdfPTable(colCountUsers);
tableUsers.HorizontalAlignment = 1;
tableUsers.WidthPercentage = 100;
int[] colWidthsUsers = new int[gvUsers.Columns.Count];
PdfPCell cellUsers;
string cellTextUsers;
for (int colIndexUsers = 0; colIndexUsers < colCountUsers; colIndexUsers++)
{
tableUsers.SetWidths(new int[] { 0, 40, 120, 110, 60, 60, 100 });
cellTextUsers = Server.HtmlDecode(gvProducts.HeaderRow.Cells[colIndexUsers].Text);
BaseFont bfUsers = BaseFont.CreateFont(
BaseFont.HELVETICA,
BaseFont.CP1252,
BaseFont.EMBEDDED,
false);
iTextSharp.text.Font fontUsers = new iTextSharp.text.Font(bfUsers, 10, iTextSharp.text.Font.BOLD, BaseColor.WHITE);
cellUsers = new PdfPCell(new Phrase(cellTextUsers.Replace("<br />", Environment.NewLine), fontUsers));
cellUsers.HorizontalAlignment = Element.ALIGN_CENTER;
cellUsers.VerticalAlignment = Element.ALIGN_MIDDLE;
cellUsers.FixedHeight = 45f;
cellUsers.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#a52a2a"));
tableUsers.AddCell(cellUsers);
}
for (int rowIndexUsers = 0; rowIndexUsers < gvUsers.Rows.Count; rowIndexUsers++)
{
if (gvUsers.Rows[rowIndexUsers].RowType == DataControlRowType.DataRow)
{
for (int j = 0; j < gvUsers.Columns.Count - 1; j++)
{
cellTextUsers = Server.HtmlDecode(gvUsers.Rows[rowIndexUsers].Cells[j].Text);
cellUsers = new PdfPCell(new Phrase(cellTextUsers, FontFactory.GetFont("PrepareForExport", 8)));
cellUsers.HorizontalAlignment = Element.ALIGN_CENTER;
cellUsers.VerticalAlignment = Element.ALIGN_MIDDLE;
cellUsers.FixedHeight = 25f;
tableUsers.AddCell(cellUsers);
}
}
}
Document pdfDocUsers = new Document(PageSize.A3.Rotate(), 30f, 30f, 30f, 0f);
PdfWriter.GetInstance(pdfDocUsers, Response.OutputStream);
pdfDocUsers.Open();
tableUsers.HeaderRows = 1;
iTextSharp.text.Font fdefaultUsers = FontFactory.GetFont("Verdana", 18, iTextSharp.text.Font.BOLD, BaseColor.BLUE);
string sUsers = "Users";
pdfDocUsers.Add(new Paragraph(sUsers, fdefaultUsers));
pdfDocUsers.Add(tableUsers);
pdfDocUsers.Close();
//end pdf gridview number two
//in first pdf gridview
//add the table to the document
pdfDoc.Add(table);
pdfDoc.Add(tableUsers);
int colCount1 = gvProducts1.Columns.Count - 1;
//Create a table
PdfPTable table1 = new PdfPTable(colCount1);
table1.HorizontalAlignment = 1;
table1.WidthPercentage = 100;
//create an array to store column widths
int[] colWidths1 = new int[gvProducts1.Columns.Count];
PdfPCell cell1;
string cellText1;
//create the header row
for (int colIndex1 = 0; colIndex1 < colCount1; colIndex1++)
{
table1.SetWidths(new int[] { 0, 40, 120, 110, 60, 60, 100, 90, 100, 50, 50, 50, 40, 30, 260, 200, 0 });
//fetch the header text
cellText1 = Server.HtmlDecode(gvProducts1.HeaderRow.Cells[colIndex1].Text);
//create a new cell with header text
BaseFont bf1 = BaseFont.CreateFont(
BaseFont.HELVETICA,
BaseFont.CP1252,
BaseFont.EMBEDDED,
false);
iTextSharp.text.Font font1 = new iTextSharp.text.Font(bf, 10, iTextSharp.text.Font.BOLD, BaseColor.WHITE);
cell1 = new PdfPCell(new Phrase(cellText.Replace("<br />", Environment.NewLine), font));
cell1.HorizontalAlignment = Element.ALIGN_CENTER;
cell1.VerticalAlignment = Element.ALIGN_MIDDLE;
cell1.FixedHeight = 45f;
//set the background color for the header cell
cell1.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#a52a2a"));
//add the cell to the table. we dont need to create a row and add cells to the row
//since we set the column count of the table to 4, it will automatically create row for
//every 4 cells
table1.AddCell(cell1);
}
//export rows from GridView to table
for (int rowIndex1 = 0; rowIndex1 < gvProducts1.Rows.Count; rowIndex1++)
{
if (gvProducts.Rows[rowIndex1].RowType == DataControlRowType.DataRow)
{
for (int j1 = 0; j1 < gvProducts1.Columns.Count - 1; j1++)
{
//fetch the column value of the current row
cellText1 = Server.HtmlDecode(gvProducts1.Rows[rowIndex1].Cells[j].Text);
//create a new cell with column value
cell1 = new PdfPCell(new Phrase(cellText1, FontFactory.GetFont("PrepareForExport", 8)));
cell1.HorizontalAlignment = Element.ALIGN_CENTER;
cell1.VerticalAlignment = Element.ALIGN_MIDDLE;
cell1.FixedHeight = 25f;
//Set Color of Alternating row
if (rowIndex1 % 2 != 0)
{
cell1.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#f5f5dc"));
}
else
{
cell1.BackgroundColor = new BaseColor(System.Drawing.ColorTranslator.FromHtml("#fcfcfc"));
}
//add the cell to the table
table1.AddCell(cell1);
}
}
}
//Create the PDF Document
//open the stream
//add the table to the document
pdfDoc.Add(table1);
//close the document stream
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;" + DateTime.Now + ".pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();

iTextSharp Image minimum Table cell height

I am trying to append images to a PDF document, but the image width must = doc.PageSize.Width and height in ratio with the image width.
I am appending individual images, each in its own table and in a cell using the following method
public void AddImage(Document doc, iTextSharp.text.Image Image)
{
PdfPTable table = new PdfPTable(1);
table.WidthPercentage = 100;
table.TotalWidth = doc.PageSize.Width;
PdfPCell c = new PdfPCell(Image, true);
c.Border = PdfPCell.NO_BORDER;
c.Padding = 5;
c.FixedHeight = (doc.PageSize.Width / Image.Width) * Image.Height;
c.MinimumHeight = (doc.PageSize.Width / Image.Width) * Image.Height;
table.AddCell(c);
doc.Add(table);
}
The Document code part (Do not think this is necessary though):
using (PDFBuilder pdf = new PDFBuilder())
{
using (var doc = new Document())
{
PdfWriter writer = PdfWriter.GetInstance(doc, Response.OutputStream);
doc.Open();
var image = iTextSharp.text.Image.GetInstance(Request.MapPath("~/Images/Nemo.jpg"));
pdf.AddImage(doc, image);
pdf.AddImage(doc, image);
pdf.AddImage(doc, image);
}
}
What I want is for the images to be 100% width, and if not, the image must append on the next page.
This is currently what I am getting
And this is what I want
Any help would be greatly appreciated, thank you in advance!
Got It!
This line needed to be added:
c.Image.ScaleToFitHeight = false;
My Method
public void AddImage(Document doc, iTextSharp.text.Image Image)
{
PdfPTable table = new PdfPTable(1);
table.WidthPercentage = 100;
PdfPCell c = new PdfPCell(Image, true);
c.Border = PdfPCell.NO_BORDER;
c.Padding = 5;
c.Image.ScaleToFitHeight = false; /*The new line*/
table.AddCell(c);
doc.Add(table);
}

Generating PDF from a DataGridView in Winforms

I'm attempting to create a PDF from a DataGridView populated from a database.
I have just started trying to learn how to use iTextSharp to accomplish this.
The result of my code is a PDF that will not open. I get an error saying "File cannot be opened"
Here is my code to generate the PDF
void SendToPDF(string heading, string filename)
{
try
{
Document doc = new Document(PageSize.A4.Rotate(), 30, 30, 20, 20);
string myDocs = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
if (!Directory.Exists(myDocs + #"\Production Reports"))
Directory.CreateDirectory(myDocs + #"\Production Reports");
PdfWriter.GetInstance(doc, new FileStream(myDocs + #"\Production Reports\" + filename + ".pdf", FileMode.Append, FileAccess.Write));
iTextSharp.text.Font titleFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 14.0F, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
iTextSharp.text.Font tableFont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12.0F, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
iTextSharp.text.Font headerfont = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 12.0F, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
PdfPTable table = new PdfPTable(GridView.Columns.Count);
//table.TotalWidth = GridView.Width;
//There are ALWAYS 10 columns
float[] widths = new float[] { GridView.Columns[0].Width, GridView.Columns[1].Width, GridView.Columns[2].Width,
GridView.Columns[3].Width, GridView.Columns[4].Width, GridView.Columns[5].Width,
GridView.Columns[6].Width, GridView.Columns[7].Width, GridView.Columns[8].Width,
GridView.Columns[9].Width };
table.SetWidths(widths);
table.HorizontalAlignment = 1; // 0 - left, 1 - center, 2 - right;
table.SpacingBefore = 2.0F;
PdfPCell cell = null;
doc.Open();
Phrase p = new Phrase(new Chunk(heading, titleFont));
doc.Add(p);
foreach (DataGridViewColumn c in GridView.Columns)
{
cell = new PdfPCell(new Phrase(new Chunk(c.HeaderText, headerfont)));
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
table.AddCell(cell);
}
if (GridView.Rows.Count > 0)
{
for (int i = 0; i < GridView.Rows.Count - 1; i++)
{
for (int j = 0; j < GridView.Columns.Count - 1; j++)
{
cell = new PdfPCell(new Phrase(GridView.Rows[i].Cells[j].Value.ToString(), tableFont));
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
table.AddCell(cell);
}
}
}
doc.Add(table);
doc.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message + "\r\n" + ex.StackTrace, "Error Generating PDF", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
I'm guessing my problem has to do with setting column widths, but I'm not sure. One time, and only one time..I saw an error when I tried to open the PDF that said "illegal floating point division by 0" or something along those lines.
Any help is greatly appreciated.
It may sound obvious, but your program isn't running and locking the pdf file to its process thus preventing adobe pdf reader from reading it is it?
private void jbtnPdf_Click(object sender, EventArgs e)
{
try
{
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Filter = "All Files | *.* ";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string path = saveFileDialog.FileName;
Document pdfdoc = new Document(PageSize.A4); // Setting the page size for the PDF
PdfWriter writer = PdfWriter.GetInstance(pdfdoc, new FileStream(path + ".pdf", FileMode.Create)); //Using the PDF Writer class to generate the PDF
writer.PageEvent = new PDFFooter();
// Opening the PDF to write the data from the textbox
PdfPTable table = new PdfPTable(jdgvChild.Columns.Count);
//table.TotalWidth = GridView.Width;
float[] widths = new float[] { jdgvChild.Columns[0].Width, jdgvChild.Columns[1].Width, jdgvChild.Columns[2].Width,
jdgvChild.Columns[3].Width, jdgvChild.Columns[4].Width, jdgvChild.Columns[5].Width,
jdgvChild.Columns[6].Width, jdgvChild.Columns[7].Width};
table.SetWidths(widths);
table.HorizontalAlignment = 1; // 0 - left, 1 - center, 2 - right;
table.SpacingBefore = 2.0F;
PdfPCell cell = null;
pdfdoc.Open();
//doc.Open();
// Phrase p = new Phrase(new Chunk(heading, titleFont));
// doc.Add(p);
foreach (GridViewDataColumn c in jdgvChild.Columns)
{
cell = new PdfPCell(new Phrase(new Chunk(c.HeaderText)));
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
table.AddCell(cell);
}
if (jdgvChild.Rows.Count > 0)
{
for (int i = 0; i < jdgvChild.Rows.Count; i++)
{
PdfPCell[] objcell = new PdfPCell[jdgvChild.Columns.Count];
for (int j = 0; j < jdgvChild.Columns.Count-1; j++)
{
cell = new PdfPCell(new Phrase(jdgvChild.Rows[i].Cells[j].Value.ToString()));
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
cell.VerticalAlignment = PdfPCell.ALIGN_CENTER;
// table.AddCell(cell);
//lstCells.Add(cell);
objcell[j] = cell;
}
PdfPRow newrow = new PdfPRow(objcell);
table.Rows.Add(newrow);
}
}
pdfdoc.Add(table);
MessageBox.Show("Pdf Generation Successfully.");
pdfdoc.Close();
}
}
catch (Exception ex)
{
MessageBox.Show("Error in pdf Generation.");
}
}

print an icard in pdf using itextsharp

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);

Code isn't drawing a horizontal line in my PDF

I'm trying to add a horizontal line on top to divide the header text from the actual values in my pdf file:
Here's my code:
public class StudentList
{
public void PrintStudentList(int gradeParaleloID)
{
StudentRepository repo = new StudentRepository();
var students = repo.FindAllStudents()
.Where(s => s.IDGradeParalelo == gradeParaleloID);
try
{
Document document = new Document(PageSize.LETTER);
PdfWriter writer = PdfWriter.GetInstance(document, new FileStream(Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory) + "\\Alumnos.pdf", FileMode.Create));
document.Open();
PdfContentByte cb = writer.DirectContent;
cb.SetLineWidth(2.0f); // Make a bit thicker than 1.0 default
cb.SetGrayStroke(0.95f); // 1 = black, 0 = white
cb.MoveTo(20, 30);
cb.LineTo(400, 30);
cb.Stroke();
PdfPTable table = new PdfPTable(3);
float[] widths = new float[] { 0.6f, 0.75f, 2f };
table.SetWidths(widths);
PdfPCell numeroCell = new PdfPCell(new Phrase("Nro."));
numeroCell.Border = 0;
numeroCell.HorizontalAlignment = 0;
table.AddCell(numeroCell);
PdfPCell codigoCell = new PdfPCell(new Phrase("RUDE"));
codigoCell.Border = 0;
codigoCell.HorizontalAlignment = 0;
table.AddCell(codigoCell);
PdfPCell nombreCell = new PdfPCell(new Phrase("Apellidos y Nombres"));
nombreCell.Border = 0;
nombreCell.HorizontalAlignment = 0;
table.AddCell(nombreCell);
int c = 1;
foreach (var student in students)
{
PdfPCell cell = new PdfPCell(new Phrase(c.ToString()));
cell.Border = 0;
cell.HorizontalAlignment = 0;
table.AddCell(cell);
cell = new PdfPCell(new Phrase(student.Rude.ToString()));
cell.Border = 0;
cell.HorizontalAlignment = 0;
table.AddCell(cell);
cell = new PdfPCell(new Phrase(student.LastNameFather + " " + student.LastNameMother + " " + student.Name));
cell.Border = 0;
cell.HorizontalAlignment = 0;
table.AddCell(cell);
c++;
}
table.SpacingBefore = 20f;
table.SpacingAfter = 30f;
document.Add(table);
document.Close();
}
catch (DocumentException de)
{
Debug.WriteLine(de.Message);
}
catch (IOException ioe)
{
Debug.WriteLine(ioe.Message);
}
}
}
I don't understand why the cb.Stroke() isn't working. Any suggestions?
Drawing with iTextSharp's PdfContentByte class can be a little confusing. The height is actually relative to the bottom, not the top. So the top of the page is not 0f, but instead is actually document.Top, which on your page size of PageSize.LETTER is 726f. So if you want to draw your line 30 units from the top, try:
cb.MoveTo(20, document.Top - 30f);
cb.LineTo(400, document.Top - 30f);
Just curious -- why do it the hard way instead of using table borders? (I noticed you set your borders to 0) Trying to space out lines by hand is the biggest pain. If you ever move content in your PDF around, you'll have to make sure your measurements still work.
Try this:
numeroCell.Border = 0;
numeroCell.BorderColorBottom = new BaseColor(System.Drawing.Color.Black);
numeroCell.BorderWidthBottom = 1f;
codigoCell.Border = 0;
codigoCell.BorderColorBottom = new BaseColor(System.Drawing.Color.Black);
codigoCell.BorderWidthBottom = 1f;
nombreCell.Border = 0;
nombreCell.BorderColorBottom = new BaseColor(System.Drawing.Color.Black);
nombreCell.BorderWidthBottom = 1f;
That should give you a nice solid black line under your header row, no measurements needed:

Categories