I am having trouble trying to define an iTextSharp Font object that I can re-use throughout a class.
My first attempt was to use the FontFactory.GetFont method in 2 private methods that create PdfPCell objects:
FontFactory.GetFont("helvetica", 8)
The problem with this is that only one of the methods prints the font correctly, the other method would not print the inner text of the cell.
Next I tried to create a static field in the class representing the font:
private static Font _standardCellFont;
public static PdfPCell CreateTableHeaderCell(string cellText, int colspan = 1)
{
var innerCellText = new Phrase(cellText, PdfSupport._standardCellFont);
innerCellText.Font.Color = BaseColor.WHITE;
return new PdfPCell(innerCellText)
{
Colspan = colspan,
PaddingLeft = 5,
PaddingRight = 5,
FixedHeight = 10,
BackgroundColor = BaseColor.BLACK,
VerticalAlignment = Element.ALIGN_CENTER
};
}
public static PdfPCell CreateTableCell(string cellText, int colspan = 1, int rowspan = 1, bool bold = false, float minHeight = 0)
{
var cellInnerText =
bold ?
new Phrase(cellText, FontFactory.GetFont("helvetica", 8, Font.BOLD)) :
new Phrase(cellText, PdfSupport._standardCellFont);
return new PdfPCell(cellInnerText)
{
Border = Rectangle.NO_BORDER,
Colspan = colspan,
Rowspan = rowspan,
PaddingTop = 1,
PaddingBottom = 1,
PaddingLeft = 5,
PaddingRight = 5,
MinimumHeight = minHeight,
VerticalAlignment = Element.ALIGN_CENTER
};
}
The result of this is that neither of the methods print the cell text.
I don't think I really understand what is happening when I create a font object, my goal is to be able to define a few common fonts and basic properties (Size, Bold) that I can then re-use throughout my class, however from my usage it appears that a font object cannot be persisted in this way.
How strange. They can, and SHOULD, be shared. Are the characters you're trying to draw all in WInAnsiEncoding (mostly the first 256 characters of Unicode).
Ah! I suspect you may be running into an ALIGNMENT issue.
Valid settings for VerticalAlignment:
Element.ALIGN_TOP
Element.ALIGN_MIDDLE
Element.ALIGN_BOTTOM
Element.ALIGN_CENTER is strictly for horizontal alignment. I'm not sure that would make your text vanish, but it's certainly worth looking into.
PS: I believe you can even reuse Font and BaseFont objects across documents, though I haven't tried it myself.
Related
I have an acroform on page 1 of my document. I am creating a blank second page and i would like to show one of the fields on this page as well. If the user changes the value of this field on either of the pages, i want them both to show the new value. I found a few posts that are showing this type of solution but it doesn't work as expected:
PdfFormField fNotes = PdfFormField.CreateTextField(writer, false, false, 500);
string fieldNotes = "tfNotes";
fNotes.FieldName = fieldNotes;
PdfFormField widgetNotes = PdfFormField.CreateEmpty(writer);
PdfPCell notesCell = new PdfPCell(new Paragraph("test", helv8))
{
BorderWidthLeft = 0,
BorderWidthRight = 0,
BorderWidthTop = 0,
BorderWidthBottom = .5f
};
TextField tField = new TextField(writer, new iTextSharp.text.Rectangle(0, 0, 100, 100), fieldNotes);
writer.AddAnnotation(fNotes);
writer.AddAnnotation(widgetNotes);
In this example, the field on page 1 is named tfNotes. If i understand correctly, i need to create a second widget reference to the acrofield. I think the above code would be for a field that doesn't already exist, in my case it does. Is there an easier way to grab a field by name on page 1 and create a duplicate reference to it on page 2?
Thank you for your time!
EDIT:
This works as expected when i take the table out of the equation, but once i try to put the duplicated field into the PdfPCell it shows up on the page at 0,0 with a width and height of 0. For some reason the rectangle of the cell is returning as 0,0,0,0.
PdfPCell notesCell = new PdfPCell()
{
BorderWidthLeft = 0,
BorderWidthRight = 0,
BorderWidthTop = 0,
BorderWidthBottom = .5f
};
//Notes Cell Rectangle
float llxNotes = notesCell.GetLeft(0);
float llyNotes = notesCell.GetBottom(0);
float urxNotes = notesCell.GetRight(0);
float uryNotes = notesCell.GetTop(0);
//Notes Duplicate
string fieldNotesName = "tfQuoteNotes";
TextField tField = new TextField(writer, new iTextSharp.text.Rectangle(llxNotes, llyNotes, urxNotes, uryNotes), fieldNotesName)
{
FieldName = fieldNotesName
};
tField.SetRotationFromPage(doc.PageSize);
writer.AddAnnotation(tField.GetTextField());
I think all i need to do now is find the correct rectangle coords for the cell.
So the part i was missing was a CellEvent, which i don't completely understand why, but here is the final working snippet for anyone who needs it:
PdfPCell notesCell = new PdfPCell()
{
BorderWidthLeft = 0,
BorderWidthRight = 0,
BorderWidthTop = 0,
BorderWidthBottom = .5f
};
//Notes Cell Rectangle
float llxNotes = notesCell.GetLeft(0);
float llyNotes = notesCell.GetBottom(0);
float urxNotes = notesCell.GetRight(0);
float uryNotes = notesCell.GetTop(0);
//Notes Duplicate
string fieldNotesName = "tfQuoteNotes";
TextField tField = new TextField(writer, new iTextSharp.text.Rectangle(llxNotes, llyNotes, urxNotes, uryNotes), fieldNotesName)
{
FieldName = fieldNotesName
};
tField.SetRotationFromPage(doc.PageSize); //Needed since this page is rotated 90 from the first page
iTextSharp.text.pdf.events.FieldPositioningEvents events = new iTextSharp.text.pdf.events.FieldPositioningEvents(writer, tField.GetTextField());
writer.AddAnnotation(tField.GetTextField());
notesCell.CellEvent = events; //This somehow ignores the original rectangle (0,0,0,0) in the TextField definition above and changes it to the cell's rectangle
Below is the code which i am using. I want a table with width 40, & inside that table, there is another table with width 25. Whatever value i give to inner table, it seems to have a fixed width. It tried with different options like 'LockedWidth', but that makes the table super small. Could please anyone help in that.
PdfPTable outerTable = new PdfPTable(1) { HorizontalAlignment = 0 };
outerTable.TotalWidth = 40;
PdfPCell outerTableColumn = new PdfPCell()
{
FixedHeight = 20,
BackgroundColor = new BaseColor(217, 83, 79)
};
PdfPTable innerTable = new PdfPTable(1) { HorizontalAlignment = 0 };
innerTable.TotalWidth = 28;
PdfPCell innerTableColumn = new PdfPCell()
{
FixedHeight = 15,
BackgroundColor = new BaseColor(92, 184, 92)
};
innerTable.AddCell(innerTableColumn);
outerTableColumn.AddElement(innerTable);
outerTable.AddCell(outerTableColumn);
I can't try it right now, but I think this should help:
innerTable.WidthPercentage = 62.5f;
I am pretty new in iTextSharp and I have the following situation: I am creating a PDF that contains an header and a footer (for the header and footer creation I am using a class that extends PdfPageEventHelper and I have override the OnStartPage() and the OnEndPage() method, it work fine).
Now my problem is that I have to insert as Page X of Y into my footer. Where X**is the **current page number and Y is the total page number. The value of Y is not fixed (because the length of my PDF is not known in advance because it depends depends on the length of the content and can differ from PDF to PDF). How can I handle this situation? (inserting the correct Y value in each footer?)
Searching online I have find this tutorial (that is for Java iText but maybe it is not so different from iTextSharp version): http://itextpdf.com/examples/iia.php?id=104
In this example it create a PDF and its header contains something like Page X of Y.
I am trying to understand this example (and translate it for iTextSharp) but I have some doubts about how it work (and if it is a real solution for my problem).
From what I can understand it perform the following operations:
Into the class that extends PdfPageEventHelper it is declared a PdfTemplate object
PdfTemplate total;
I think that maybe it handles the total pages number that are into my PDF document, but reading the official documentation I have not many information about what exactly do this class: http://api.itextpdf.com/itext/com/itextpdf/text/pdf/PdfTemplate.html
I am trying to do something similar into my class that extends PdfPageEventHelper but I can't do it.
This is my not working code:
public class PdfHeaderFooter : PdfPageEventHelper
{
// The template with the total number of pages:
PdfTemplate total;
private static int numPagina = 1;
public Image CellImage;
private string folderImages;
private string _sourceId;
public PdfHeaderFooter(string _folderImages, string sourceId)
{
folderImages = _folderImages;
_sourceId = sourceId;
}
/* Creates the PdfTemplate that will hold the total number of pages.
* Write on top of document
* */
public override void OnOpenDocument(PdfWriter writer, Document document)
{
base.OnOpenDocument(writer, document);
// (Nobili) Page Number:
total = writer.DirectContent.CreateTemplate(30, 16);
//PdfPTable tabFot = new PdfPTable(new float[] { 1F });
PdfPTable tabFot = new PdfPTable(2);
tabFot.WidthPercentage = 98;
tabFot.SpacingAfter = 10F;
PdfPCell cell;
//tabFot.TotalWidth = 300F;
cell = new PdfPCell(new Phrase("Header"));
tabFot.AddCell(cell);
tabFot.WriteSelectedRows(0, -1, 150, document.Top, writer.DirectContent);
}
// write on end of each page
public override void OnEndPage(PdfWriter writer, Document document)
{
base.OnEndPage(writer, document);
int pageN = writer.PageNumber;
String text = "Page " + pageN + " of ";
//PdfPTable tabFoot = new PdfPTable(new float[] { 1F });
PdfPTable tabFoot = new PdfPTable(3);
tabFoot.TotalWidth = document.Right - document.Left;
tabFoot.DefaultCell.Border = PdfPCell.NO_BORDER;
tabFoot.DefaultCell.CellEvent = new RoundedBorder();
PdfPTable innerTable = new PdfPTable(2);
innerTable.SetWidths(new int[] { 247, 246 });
innerTable.TotalWidth = document.Right - document.Left;
innerTable.DefaultCell.Border = PdfPCell.NO_BORDER;
PdfPCell innerCellLeft = new PdfPCell(new Phrase("Early Warning - Bollettino")) { Border = PdfPCell.NO_BORDER, Padding = 5, MinimumHeight = 20, HorizontalAlignment = Element.ALIGN_LEFT };
//PdfPCell innerCellRight = new PdfPCell(new Phrase("Pag. " + numPagina + "/5")) { Border = PdfPCell.NO_BORDER, Padding = 5, MinimumHeight = 20, HorizontalAlignment = Element.ALIGN_RIGHT };
PdfPCell innerCellCenter = new PdfPCell(new Phrase(text)) { Border = PdfPCell.NO_BORDER, Padding = 5, MinimumHeight = 20, HorizontalAlignment = Element.ALIGN_RIGHT };
PdfPCell innerCellRight = new PdfPCell(Image.GetInstance(total)) { Border = PdfPCell.NO_BORDER, Padding = 5, MinimumHeight = 20, HorizontalAlignment = Element.ALIGN_RIGHT };
innerTable.AddCell(innerCellLeft);
innerTable.AddCell(innerCellRight);
tabFoot.AddCell(innerTable);
tabFoot.WriteSelectedRows(0, -1, document.Left, document.Bottom, writer.DirectContent);
numPagina++;
}
// write on start of each page
public override void OnStartPage(PdfWriter writer, Document document)
{
base.OnStartPage(writer, document);
PdfPTable tabHead = new PdfPTable(3);
tabHead.SetWidths(new int[] { 165, 205, 125 });
//tabHead.TotalWidth = 460F;
tabHead.TotalWidth = document.Right - document.Left; // TotalWidth = 495
tabHead.WidthPercentage = 98;
PdfPCell cell1 = new PdfPCell(iTextSharp.text.Image.GetInstance(folderImages + "logoEarlyWarning.png"), true) { Border = PdfPCell.BOTTOM_BORDER };
tabHead.AddCell(cell1);
//tabHead.AddCell(new PdfPCell(new Phrase("CELL 1:")) { Border = PdfPCell.BOTTOM_BORDER, Padding = 5, MinimumHeight = 50, PaddingTop = 15, });
tabHead.AddCell(new PdfPCell(new Phrase("CELL 2:")) { Border = PdfPCell.BOTTOM_BORDER, Padding = 5, MinimumHeight = 50, PaddingTop = 15 });
if(_sourceId == "NVD")
{
iTextSharp.text.Image logo = iTextSharp.text.Image.GetInstance(folderImages + "nvdLogo.png");
logo.ScalePercent(48f);
//PdfPCell cell3 = new PdfPCell(iTextSharp.text.Image.GetInstance(folderImages + "nvdLogo.png"), true) { Border = PdfPCell.BOTTOM_BORDER, PaddingBottom = 25 };
PdfPCell cell3 = new PdfPCell(logo) { Border = PdfPCell.BOTTOM_BORDER, PaddingLeft = 50 };
tabHead.AddCell(cell3);
}
else if(_sourceId == "DeepSight")
{
PdfPCell cell3 = new PdfPCell(iTextSharp.text.Image.GetInstance(folderImages + "DSLogo.jpg"), true) { Border = PdfPCell.BOTTOM_BORDER };
tabHead.AddCell(cell3);
}
//tabHead.AddCell(new PdfPCell(new Phrase("CELL 3:")) { Border = PdfPCell.BOTTOM_BORDER, Padding = 5, MinimumHeight = 50, PaddingTop = 15 });
tabHead.WriteSelectedRows(0, -1, document.Left, document.Top, writer.DirectContent);
}
//write on close of document
public override void OnCloseDocument(PdfWriter writer, Document document)
{
base.OnCloseDocument(writer, document);
}
}
}
I want put in the footer something like the Page X of Y as shown in the tutorial
I tryied to do the following thing:
1) I declared the PdfTemplate total; object as field of my class and I initialize it into my OnOpenDocument() method
total = writer.DirectContent.CreateTemplate(30, 16);
2) Into my OnEndPage() method I put:
String text = "Page " + pageN + " of ";
and I created the following table to show the Page X of Y
PdfPCell innerCellLeft = new PdfPCell(new Phrase("Early Warning - Bollettino")) { Border = PdfPCell.NO_BORDER, Padding = 5, MinimumHeight = 20, HorizontalAlignment = Element.ALIGN_LEFT };
PdfPCell innerCellCenter = new PdfPCell(new Phrase(text)) { Border = PdfPCell.NO_BORDER, Padding = 5, MinimumHeight = 20, HorizontalAlignment = Element.ALIGN_RIGHT };
PdfPCell innerCellRight = new PdfPCell(Image.GetInstance(total)) { Border = PdfPCell.NO_BORDER, Padding = 5, MinimumHeight = 20, HorizontalAlignment = Element.ALIGN_RIGHT };
But it don't work and throw me an exception
What could be the problem in my code?
You are copy/pasting code without reading the documentation that comes with the examples. Moreover you are completely ignoring the C# version of the examples from my book. I have paid good money to a C# developer to port these examples. It feels as if that money was thrown away. You can find the example you tried to port yourself here: http://tinyurl.com/itextsharpIIA2C05
Error #1: you are adding content in the OnStartPage() method. That is forbidden! This is documented on many places. See for instance this answer copied from page 150 of the official documentation:
FAQ Why is it not advised to add content in the onStartPage() method? You'll remember from section 5.2.4 that iText ignores newPage() calls when the current page is empty. This method is executed — or ignored — when you call it explicitly from your code, but it's also invoked implicitly from within iText on multiple occasions. It's important that it's ignored for empty pages; otherwise you'd end up with plenty of unwanted new pages that are unintentionally left blank. If you add content in an onStartPage() method, there's always a risk of having unwanted pages. Consider it more safe to reserve the onEndPage() method for adding content.
Error #2: you are adding content in the OnOpenDocument() method. Why would that make sense?
Error #3: you create the total object because you want to create a place holder that can be added to each page. Once you know the total number of pages, you want to fill out that number on that place holder. However: I don't see you doing this anywhere. The appropriate place to do this, is obviously in the OnCloseDocument() even. This event is triggered right before the document is closed, so at that moment, the total number of pages is known. This is, as Sherlock Holmes would say, elementary, my dear!
I am using the iTextSharp.dll with the following code:
var Title = "This is title";
var Description = "This is description";
Innertable.AddCell(new PdfPCell(new Phrase(string.Format("{0} {1}", Title, Description.Trim()), listTextFont)) { BackgroundColor = new BaseColor(233, 244, 249), BorderWidth = 0, PaddingTop = 4, PaddingLeft = -240, PaddingBottom = 5, HorizontalAlignment = Element.ALIGN_LEFT });
Can we set different font colors for title and description, but only using single cell (ie without creating a new table)?
Any help in this matter would be greatly appreciated.
What you want to do is create 2 Chunk objects, and then combine these into 1 Phrase which you will add to the cell.
var blackListTextFont = FontFactory.GetFont("Arial", 28, Color.BLACK);
var redListTextFont = FontFactory.GetFont("Arial", 28, Color.RED);
var titleChunk = new Chunk("Title", blackListTextFont);
var descriptionChunk = new Chunk("Description", redListTextFont);
var phrase = new Phrase(titleChunk);
phrase.Add(descriptionChunk);
table.AddCell(new PdfPCell(phrase));
Have a look at http://www.mikesdotnetting.com/Article/82/iTextSharp-Adding-Text-with-Chunks-Phrases-and-Paragraphs
Try like this to set a different foreground color in a pdf cell:
var FontColour = new BaseColor(35, 31, 32);
var Calibri8 = FontFactory.GetFont("Calibri", 8, FontColour);
PdfPCell R3C2 = new PdfPCell(new Paragraph("Hello", Calibri8));
R3C2.BorderWidth = 0f;
R3C2.HorizontalAlignment = PdfPCell.ALIGN_RIGHT;
table.AddCell(R3C2);
For VB.net Use the following function
Public Function CreateFont(size As Integer, Optional style As Integer = iTextSharp.text.Font.BOLD) As iTextSharp.text.Font
Dim FontColour = New BaseColor(193, 36, 67) 'Color code
Return New iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.TIMES_ROMAN, size, style, FontColour)
End Function
Dim p As New Paragraph
p.Add(New Paragraph("Your Sentence Here", CreateFont(12, iTextSharp.text.Font.BOLDITALIC)))
pdfDoc.Add(p)
The trick is to create phrases (NOT chunks) with different fonts and add these to a parent phrase. As far as I can tell if you create chunks with different fonts and add these to a phrase, all of the text in the final phrase displays with the same font.
Here's an example which works for me:
// create the font we'll use
var fNormal = FontFactory.GetFont("Helvetica", 10f);
fNormal.SetColor(0, 0, 0);
// add phrase containing link
var pFooter = new Phrase();
// add phrase to this containing text only
var footerStart = new Phrase("Visit ");
footerStart.Font = fNormal;
pFooter.Add(footerStart);
// now create anchor and add with different font
string wolSiteUrl = "http://www.whateveryoulike.com";
Anchor wolWebSiteLink = new Anchor(wolSiteUrl, fNormal);
wolWebSiteLink.Reference = wolSiteUrl;
wolWebSiteLink.Font = fNormal;
wolWebSiteLink.Font.SetColor(242, 132, 0);
pFooter.Add(wolWebSiteLink);
// add text to go after this link
var footerEnd = new Phrase(" to view these results online.");
footerEnd.Font = fNormal;
pFooter.Add(footerEnd);
var paraFooter = new Paragraph(pFooter);
// add the phrase we've built up containing lots of little phrases to document
// (assume you have one of these ...)
doc.Add(paraFooter);
I'm having a weird problem with images in iTextSharp library.
I'm adding the image to the PdfPCell and for some reason it gets scaled up.
How do i keep it to original size?
I though that the images would be same when printed but the difference on the pic is the same on the printed version. Having to manually scale the image with ScaleXXX to get it to right seems a bit illogical and does not give a good result.
So how do I put the image in its original size inside a PdfPCell of a table without having to scale it?
Here's my code:
private PdfPTable CreateTestPDF()
{
PdfPTable table = new PdfPTable(1);
table.WidthPercentage = 100;
Phrase phrase = new Phrase("MY TITLE", _font24Bold);
table.AddCell(phrase);
PdfPTable nestedTable = new PdfPTable(5);
table.WidthPercentage = 100;
Phrase cellText = new Phrase("cell 1", _font9BoldBlack);
nestedTable.AddCell(cellText);
cellText = new Phrase("cell 2", _font9BoldBlack);
nestedTable.AddCell(cellText);
cellText = new Phrase("cell 3", _font9BoldBlack);
nestedTable.AddCell(cellText);
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(#"d:\MyPic.jpg");
image.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
PdfPCell cell = new PdfPCell(image);
cell.HorizontalAlignment = PdfPCell.ALIGN_MIDDLE;
nestedTable.AddCell(cell);
cellText = new Phrase("cell 5", _font9BoldBlack);
nestedTable.AddCell(cellText);
nestedTable.AddCell("");
string articleInfo = "Test Text";
cellText = new Phrase(articleInfo, _font8Black);
nestedTable.AddCell(cellText);
nestedTable.AddCell("");
nestedTable.AddCell("");
nestedTable.AddCell("");
table.AddCell(nestedTable);
SetBorderSizeForAllCells(table, iTextSharp.text.Rectangle.NO_BORDER);
return table;
}
static BaseColor _textColor = new BaseColor(154, 154, 154);
iTextSharp.text.Font _font8 = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, _textColor);
iTextSharp.text.Font _font8Black = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 8, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
iTextSharp.text.Font _font9 = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 9, iTextSharp.text.Font.NORMAL, _textColor);
iTextSharp.text.Font _font9BoldBlack = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 9, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
iTextSharp.text.Font _font10 = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10, iTextSharp.text.Font.NORMAL, _textColor);
iTextSharp.text.Font _font10Black = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10, iTextSharp.text.Font.NORMAL, BaseColor.BLACK);
iTextSharp.text.Font _font10BoldBlack = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 10, iTextSharp.text.Font.BOLD, BaseColor.BLACK);
iTextSharp.text.Font _font24Bold = new iTextSharp.text.Font(iTextSharp.text.Font.FontFamily.HELVETICA, 24, iTextSharp.text.Font.BOLD, _textColor);
I'm using iTextSharp v4.1.2 and I get the following behavior:
Using this code, adding the image directly to the table via the AddCell method, the image is scaled up to fit the cell:
nestedTable.AddCell(image);
Using this code, adding the image to a cell, then adding the cell to the table, the image is displayed at its original size:
PdfPCell cell = new PdfPCell(image);
cell.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
nestedTable.AddCell(cell);
Have you added the image directly to the pdf document (outside the table) just to compare/double-check the image sizes?
document.add(image);
I assume that you want the image centered in the cell with some space around it. As a last resort, you can change your image. Make it a png with a transparent background, and just make sure that there is some transparent 'margin' around all the edges of your image.
EDIT
I just downloaded the v5.0.2 and I get the same results as mentioned above. I've tried it with images that are both smaller and larger than the size of the cell, and the behavior is the same; the first method scales the image, the second method does not.
EDIT
Well, apparently I have been wrong for years about the whole DPI thing when it comes to images. I can't seem to see that it makes any difference at all what the DPI of the image is.
I created a 600x400px image at three different resolutions, 72dpi, 96 dpi, and 110 dpi. Then I added each these images to a new document that was exactly 600x400.
Dim pSize As Rectangle = New Rectangle(600, 1000)
Dim document As Document = New Document(pSize, 0, 0, 0, 0)
For each of the three image files, when added to the document with
document.add(image)
they fit the document perfectly, with no differences for the different DPI settings.
#Stewbob's answer does work, but it's only incidently related to the methods of the table.
The thing with iTextSharp is that it will behave differently depending on which constructor you use. This will (annoyingly) scale up the image to fill the cell:
PdfPCell c = new PdfPCell();
c.Add(image);
c.setHorizontalAlignment(Element.ALIGN_CENTER); // this will be ignored
But this will leave the image at the size you set it (and allow for alignment):
PdfPCell c = new PdfPCell(image);
c.setHorizontalAlignment(Element.ALIGN_CENTER);
I don't know exactly why this is, it's got something to do with the cell being in 'text mode' if you add the image in the constructor versus 'composite mode' if you add it later (in which case each object is supposed to look after it's own alignment).
Some more info (in Java, but still applies) http://tutorials.jenkov.com/java-itext/table.html#cell-modes
So if you have to mantain the size of the image in the PdfPCell you can loock at this code :
iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imageFilePath);
// Save the image width
float width = image.Width;
PdfPCell cell = new PdfPCell();
cell.AddElement(image);
// Now find the Image element in the cell and resize it
foreach (IElement element in cell.CompositeElements)
{
// The inserted image is stored in a PdfPTable, so when you find
// the table element just set the table width with the image width, and lock it.
PdfPTable tblImg = element as PdfPTable;
if (tblImg != null)
{
tblImg.TotalWidth = width;
tblImg.LockedWidth = true;
}
}
The function has a property to fit image. Only add a true
cell.AddElement(image,true);
For those asking for the overload, use this :
var imageCell = new PdfPCell(image, true);
instead of :
cell.AddElement(image,true);