iTextsharp landscape document - c#

I am trying to create Landscape PDF using iTextSharp but It is still showing portrait. I am using following code with rotate:
Document document = new Document(PageSize.A4, 0, 0, 150, 20);
FileStream msReport = new FileStream(Server.MapPath("~/PDFS/") + "Sample1.pdf", FileMode.Create);
try
{
// creation of the different writers
PdfWriter writer = PdfWriter.GetInstance(document, msReport);
document.Open();
PdfPTable PdfTable = new PdfPTable(1);
PdfTable.SpacingBefore = 30f;
PdfPCell PdfPCell = null;
Font fontCategoryheader = new Font(Font.HELVETICA, 10f, Font.BOLD, Color.BLACK);
for (int i = 0; i < 20; i++)
{
PdfPCell = new PdfPCell(new Phrase(new Chunk("Sales Manager: ", fontCategoryheader)));
PdfPCell.BorderWidth = 0;
PdfPCell.HorizontalAlignment = Element.ALIGN_LEFT;
if (i % 2 == 0)
PdfPCell.BackgroundColor = Color.LIGHT_GRAY;
PdfPCell.PaddingBottom = 5f;
PdfPCell.PaddingLeft = 2f;
PdfPCell.PaddingTop = 4f;
PdfPCell.PaddingRight = 4f;
PdfTable.AddCell(PdfPCell);
}
document.Add(PdfTable);
document.NewPage();
}
catch (Exception ex)
{
Console.Error.WriteLine(ex.Message);
}
finally
{
// we close the document
document.Close();
}
Please suggest solution.
Thanks.

Try this
Document Doc = new Document(new Rectangle(288f, 144f), 10, 10, 10, 10);
Doc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
you might also need this to expand a table to max width.
var _pdf_table = new PdfPTable(2); // table with two columns
PdfPCell hc = new PdfPCell();
_pdf_table.WidthPercentage = 100; //table width to 100per
_pdf_table.SetTotalWidth(new float[] { 25, iTextSharp.text.PageSize.A4.Rotate().Width - 25 });// width of each column
You must make sure that when setting the page size you do it before a call to Doc.Open();
Regards.

No need to initialize the Document and reset the page size...
Document doc = new Document(iTextSharp.text.PageSize.A4.Rotate(), 10, 10, 10, 10);
...will do the trick.
(4.1.6.0)

Related

how to add background color to last line of GridView

I am using iText to export GridView to pdf.
I was able to add header color to my pdf.
I would like to add background color to the last (total) line/row of pdf in the Gridview?
I am using iText library to export GridView to Pdf.
Here is my pdf function :
public void ExpToPdf_Click(object sender, EventArgs e)
{
getHTMLGridView();
}
private void getHTMLGridView()
{
BaseFont bfTimes = BaseFont.CreateFont(BaseFont.TIMES_ROMAN, BaseFont.CP1252, false);
iTextSharp.text.Font times16 = new iTextSharp.text.Font(bfTimes, 16, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
Paragraph p1 = new Paragraph("Texas Tech University", times16);
p1.Alignment = 1;
iTextSharp.text.Font times14 = new iTextSharp.text.Font(bfTimes, 14, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
Paragraph p2 = new Paragraph("Department of Institutional Research", times14);
Paragraph p3 = new Paragraph(caption.Text.ToUpper(), times14);
p2.Alignment = 1;
p3.Alignment = 1;
//iTextSharp.text.Font times10 = new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
//Paragraph p4 = new Paragraph("(Uncertified Data)", times10);
//p4.Alignment = 1;
Paragraph p5 = new Paragraph(" ");
iTextSharp.text.Font times8 = new iTextSharp.text.Font(bfTimes, 8, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.BLACK);
iTextSharp.text.Font times11 = new iTextSharp.text.Font(bfTimes, 10, iTextSharp.text.Font.NORMAL, iTextSharp.text.Color.WHITE);
iTextSharp.text.Color BackgroundColor = new iTextSharp.text.Color(System.Drawing.ColorTranslator.FromHtml("#CC0000"));
PdfPTable HeaderTable = new PdfPTable(4);
//actual width of table in points
HeaderTable.TotalWidth = 600f;
//fix the absolute width of the table
HeaderTable.LockedWidth = true;
//relative col widths in proportions - 1/3 and 2/3
float[] Headerwidths = new float[] { 1f, 1f, 1f, 1f};
HeaderTable.SetWidths(Headerwidths);
HeaderTable.HorizontalAlignment = 1;
//leave a gap before and after the table
//HeaderTable.SpacingBefore = 30f;
//HeaderTable.SpacingAfter = 30f;
foreach (TableCell cell in MyGridView.HeaderRow.Cells)
{
PdfPCell pdfCell = new PdfPCell(new Phrase(cell.Text, times11));
// Set the PDF cell backgroundcolor to GridView header row BackgroundColor color
pdfCell.BackgroundColor = BackgroundColor;
pdfCell.HorizontalAlignment = 1; //0=Left, 1=Centre, 2=Right
// Add the cell to PDF table
HeaderTable.AddCell(pdfCell);
}
PdfPTable table = new PdfPTable(4);
//actual width of table in points
table.TotalWidth = 600f;
//fix the absolute width of the table
table.LockedWidth = true;
//relative col widths in proportions
float[] widths = new float[] { 1f, 1f, 1f, 1f};
table.SetWidths(widths);
table.HorizontalAlignment = 1;
//leave a gap before and after the table
//table.SpacingBefore = 30f;
//table.SpacingAfter = 30f;
string connect = System.Web.Configuration.WebConfigurationManager.ConnectionStrings["ConnStringExtracts_IRDW"].ConnectionString;
DataSet ds = new DataSet();
using (SqlConnection conn = new SqlConnection(connect))
{
string query = "dbo.sp_FB_APPADM_IRDW";
SqlCommand cmd = new SqlCommand(query, conn);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.AddWithValue("#reportType", reportType);
cmd.Parameters.AddWithValue("#term_Code", ENRDropDownList.SelectedValue);
try
{
int i;
conn.Open();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
// Fill the DataSet.
adapter.Fill(ds);
foreach (DataRow row in ds.Tables[0].Rows)
{
for (i = 0; i < 2; i++)
{
PdfPCell pdfCell4 = new PdfPCell(new Phrase(row[i].ToString(), times8));
pdfCell4.HorizontalAlignment = 0; //0=Left, 1=Centre, 2=Right
// Add the cell to PDF table
table.AddCell(pdfCell4);
}
for (i = 2; i < ds.Tables[0].Columns.Count; i++)
{
PdfPCell pdfCell4 = new PdfPCell(new Phrase(row[i].ToString(), times8));
pdfCell4.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right
// Add the cell to PDF table
table.AddCell(pdfCell4);
}
}
}
catch (Exception ex)
{
Response.Write(ex.Message);
}
//Create the PDF Document
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
pdfDoc.SetPageSize(iTextSharp.text.PageSize.A4.Rotate());
PdfWriter.GetInstance(pdfDoc, Response.OutputStream);
//open the stream
pdfDoc.Open();
//add the table to the document
pdfDoc.Add(p1);
pdfDoc.Add(p2);
pdfDoc.Add(p3);
pdfDoc.Add(p5);
pdfDoc.Add(HeaderTable);
pdfDoc.Add(table);
//close the document stream
pdfDoc.Close();
Response.ContentType = "application/pdf";
Response.AddHeader("content-disposition", "attachment;" + "filename=Enrollment_Major_Classification.pdf");
Response.Cache.SetCacheability(HttpCacheability.NoCache);
Response.Write(pdfDoc);
Response.End();
}
}
I tried using: GridView1.Rows[GridView1.Rows.Count - 1] to get the last row of gridview. But, I did not seem to make my way around it, to add color to last row.
Any help much appreciated.
You can simply do this:
GridView1.Rows[GridView1.Rows.Count - 1].BackColor = Color.Green;
Or if the row is a FooterRow:
GridView1.FooterRow.BackColor = Color.Red;

export gridview to pdf with header and margin 0

i am facing a problem in exporting to PDF since the grid view contain an Arabic text, so i changed my code and it working, the problem is when i export it the gridview header is missing, how can i change the width of the table?, how can i export the same look and feel of the grid view to the PDF, also how can i change the margin of the exported PDF?
iTextSharp.text.pdf.PdfPTable table = new iTextSharp.text.pdf.PdfPTable(GridView1.Columns.Count);
table.RunDirection = PdfWriter.RUN_DIRECTION_LTR;
BaseFont bf = BaseFont.CreateFont("c:\\\\windows\\\\fonts\\\\tahoma.ttf", BaseFont.IDENTITY_H, true);
iTextSharp.text.Font f2 = new iTextSharp.text.Font(bf, 8, iTextSharp.text.Font.NORMAL);
for (int i = 0; i <= GridView1.Rows.Count-1; i++)
{
for (int j = 0; j <= GridView1.Columns.Count - 1; j++)
{
string cellText = Page.Server.HtmlDecode(GridView1.Rows[i].Cells[j].Text);
iTextSharp.text.pdf.PdfPCell cell = new iTextSharp.text.pdf.PdfPCell(new Phrase(100, cellText, f2));
table.AddCell(cell);
}
}
Document pdfDoc = new Document(PageSize.A4, 10f, 10f, 10f, 0f);
int[] intTblWidth = { 10, 10, 25, 50,25,25,50,10,50,10 };
table.SetWidths(intTblWidth);
table.TotalWidth = 500f;
PdfWriter.GetInstance(pdfDoc, Page.Response.OutputStream);
pdfDoc.Open();
pdfDoc.SetMargins(0, 0, 0, 0);
pdfDoc.Add(table); // add the table
pdfDoc.Close();
Page.Response.ContentType = "application/pdf";
Page.Response.AddHeader("content-disposition", "attachment;filename=GridViewExport.pdf");
Page.Response.Cache.SetCacheability(HttpCacheability.NoCache);
Page.Response.Write(pdfDoc);
Page.Response.End();
Read the link below:
You can set the margin as required
http://www.dotnetspider.com/resources/29759-Exporting-GridView-PDF.aspx
Also visit the link below....
http://www.aspsnippets.com/Articles/Export-GridView-to-PDF-and-send-PDF-File-as-email-attachment-in-ASPNet.aspx

iTextSharp SetCharacterSpacing broken when using Right Align

I have a table with two cells. The first cell is left aligned and the second cell is right aligned. I also want to change the character spacing of the text. I have found that changing the character spacing breaks the alignment so the right align text ends up outside the boundaries if the table.
I have created some test code below and the link to the output PDF is in this link
https://skydrive.live.com/redir?resid=1ECE2061CFF9124B!190&authkey=!ANcB0z_BN3N4UFo
Are there any alternatives or workarounds to getting the character spacing working well with the right alignment?
public void CharacterSpacingTest()
{
float margin = 50;
using (var stream = new MemoryStream())
{
Document document = new Document();
document.SetPageSize(new Rectangle(PageSize.A4.Width, PageSize.A4.Height));
document.SetMargins(margin, margin, 30f, 100f);
PdfWriter writer = PdfWriter.GetInstance(document, stream);
writer.CloseStream = false;
document.Open();
PdfPTable table = new PdfPTable(new float[] { 100 });
table.TotalWidth = PageSize.A4.Width - margin - margin;
table.WidthPercentage = 100f;
table.LockedWidth = true;
// Create a row that is right aligned
PdfPCell cell1 = new PdfPCell();
cell1.AddElement(new Paragraph("Hello World") { Alignment = Element.ALIGN_RIGHT });
cell1.BorderWidth = 1;
table.AddCell(cell1);
// Change the character spacing
PdfContentByte cb = writer.DirectContent;
cb.SetCharacterSpacing(1f);
// Create a row that is left aligned
PdfPCell cell2 = new PdfPCell();
cell2.AddElement(new Paragraph("Hello World"));
cell2.BorderWidth = 1;
table.AddCell(cell2);
document.Add(table);
document.Close();
Blobs.SaveToFile(Blobs.LoadFromStream(stream), #"c:\Dev\test.pdf");
}
}
I have managed to fix it by using chunks to set the character spacing. See amended code.
public void CharacterSpacingTest()
{
float margin = 50;
using (var stream = new MemoryStream())
{
Document document = new Document();
document.SetPageSize(new Rectangle(PageSize.A4.Width, PageSize.A4.Height));
document.SetMargins(margin, margin, 30f, 100f);
PdfWriter writer = PdfWriter.GetInstance(document, stream);
writer.CloseStream = false;
document.Open();
PdfPTable table = new PdfPTable(new float[] { 100 });
table.TotalWidth = PageSize.A4.Width - margin - margin;
table.WidthPercentage = 100f;
table.LockedWidth = true;
// Create a row that is right aligned
PdfPCell cell1 = new PdfPCell();
cell1.AddElement(new Paragraph(GetChunk("Hello World")) { Alignment = Element.ALIGN_RIGHT });
cell1.BorderWidth = 1;
table.AddCell(cell1);
// Create a row that is left aligned
PdfPCell cell2 = new PdfPCell();
cell2.AddElement(new Paragraph(GetChunk("Hello World")));
cell2.BorderWidth = 1;
table.AddCell(cell2);
document.Add(table);
document.Close();
Blobs.SaveToFile(Blobs.LoadFromStream(stream), #"c:\Dev\test.pdf");
}
}
private Chunk GetChunk(string text)
{
Chunk chunk = new Chunk(text);
chunk.SetCharacterSpacing(1);
return chunk;
}

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.");
}
}

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