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;
}
Related
I have this code and I want to add a table as a footer. But the problem is I cannot pass the variables:
Document doc = new Document();
doc.AddTitle("e-8D Report_" + report.OSIE8DNO + ".pdf");
PdfWriter writer = PdfWriter.GetInstance(doc, fs);
doc.SetPageSize(PageSize.A4);
doc.SetMargins(18f, 18f, 18f, 18f); // 0.25 inch margins
doc.Open();
PdfPTable table = new PdfPTable(10)
{
WidthPercentage = 100,
LockedWidth = true,
TotalWidth = 560f
};
float[] widths = new float[] { 32f, 73f, 70f, 70f, 70f, 70f, 70f, 70f, 73f, 32f };
table.SetWidths(widths);
// rest of the document
// ...
// rest of the document
// Below is the part that I want to add as footer
#region Footer
// left margin
cell = new PdfPCell(new Phrase(" ", font6))
{
Border = Rectangle.NO_BORDER
};
table.AddCell(cell);
cell = new PdfPCell(new Phrase("Reviewed & Approved by :", font6))
{
Colspan = 4,
BackgroundColor = bgBlue,
HorizontalAlignment = Element.ALIGN_LEFT,
Border = Rectangle.TOP_BORDER | Rectangle.LEFT_BORDER
};
table.AddCell(cell);
cell = new PdfPCell(new Phrase("For document approval by email, no Manual / e-Signature required &", font2))
{
Colspan = 4,
BackgroundColor = bgBlue,
HorizontalAlignment = Element.ALIGN_LEFT,
Border = Rectangle.TOP_BORDER | Rectangle.RIGHT_BORDER
};
table.AddCell(cell);
// right margin
cell = new PdfPCell(new Phrase(" ", font6))
{
Border = Rectangle.NO_BORDER
};
table.AddCell(cell);
// the rest of the cell
//...
// the rest of the cell
#endregion
doc.Add(table);
//writer.PageEvent = new PDFFooter();
doc.Close();
With this variables, I can't make the footer with PdfPageEventHelper from this source:
Footer in pdf with iTextSharp
Please help
Already got the answer. I add parameter to the PdfPageEventHelper Class:
public PdfPTable footer { get; set; }
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
document.Add(footer);
}
And call from the page (create complete table first on the page):
writer.PageEvent = new PDFHeaderFooter() { footer = table };
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);
}
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)
I want to create th following PDF layout with ITextSharp:
I use the following code to generate my table:
Document document = new Document(PageSize.A4);
MemoryStream memoryStream = new MemoryStream();
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
document.Open();
PdfPCell cell;
PdfPTable table = new PdfPTable(2);
table.SetWidths(new float[] { 450, 100 });
table.WidthPercentage = 100;
cell = new PdfPCell(new Phrase("Item cod werwerwer"));
table.AddCell(cell);
cell = new PdfPCell(new Phrase("100"));
table.AddCell(cell);
cell = new PdfPCell(new Phrase(string.Empty));
table.AddCell(cell);
cell = new PdfPCell(new Phrase("100"));
table.AddCell(cell);
document.Add(table);
writer.CloseStream = false;
document.Close();
memoryStream.Position = 0;
return memoryStream.ToArray();
How can I force table to cover full page height without use fixed height value?
you can use table.ExtendLastRow = true;
Tables flow, that's just what they do. If you want to change the height then you're going to need to use fixed values. You could calculate these fixed values at runtime by trying to figure out what the height of some text will be in a given cell at a given width using a given font. Or you could just fix it at a magic number which is what the code below does.
At the top is the magic constant. When we create the document we specify 0 for all margins so that we fill the entire page. You can change this but you'll have to adjust the calculations below. Then in the first row we set one of the cell's MinimumHeight to the page's height minus the constant and in the second row we set one of the cell's height to the constant.
//Fixed height of last cell
float LAST_CELL_HEIGHT = 50f;
//Create our document with zero margins
Document document = new Document(PageSize.A4, 0, 0, 0, 0);
FileStream fs = new FileStream(Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "A4.pdf"), FileMode.Create, FileAccess.Write, FileShare.Read);
PdfWriter writer = PdfWriter.GetInstance(document, fs);
document.Open();
PdfPCell cell;
PdfPTable table = new PdfPTable(2);
table.SetWidths(new float[] { 450, 100 });
table.WidthPercentage = 100;
cell = new PdfPCell(new Phrase("Item cod werwerwer"));
//Set the first cell's height to the document's full height minus the last cell
cell.MinimumHeight = document.PageSize.Height - LAST_CELL_HEIGHT;
table.AddCell(cell);
cell = new PdfPCell(new Phrase("100"));
table.AddCell(cell);
cell = new PdfPCell(new Phrase(string.Empty));
//Set the last cell's height
cell.MinimumHeight = LAST_CELL_HEIGHT;
table.AddCell(cell);
cell = new PdfPCell(new Phrase("100"));
table.AddCell(cell);
document.Add(table);
writer.CloseStream = false;
document.Close();
fs.Close();
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: