Writing Arabic Text to PDF using ITextSharp - c#

I'm trying to write some text to a background image and save it as PDF, I'm using iTextSharp and the following Code:
var image = System.Drawing.Image.FromFile("resources\\bg2.png");
Document document = new Document();
var pageSize = new iTextSharp.text.Rectangle((1122*75)/100, (793 * 75) / 100);
document.SetPageSize(pageSize);
iTextSharp.text.Image bg = iTextSharp.text.Image.GetInstance(image,System.Drawing.Imaging.ImageFormat.Png);
bg.Alignment = iTextSharp.text.Image.UNDERLYING;
var writter = PdfWriter.GetInstance(document, new FileStream("file.pdf", FileMode.OpenOrCreate));
document.Open();
document.Open();
bg.SetAbsolutePosition(0, 0);
document.NewPage();
document.Add(bg);
BaseFont Tajawal = BaseFont.CreateFont(#"Resources\Tajawal-Medium 500.ttf", BaseFont.IDENTITY_H, BaseFont.EMBEDDED);
Paragraph paragraphTable1 = new Paragraph();
paragraphTable1.SpacingAfter = 15;
PdfContentByte cb = writter.DirectContent;
PdfPTable table = new PdfPTable(1);
table.DefaultCell.NoWrap = false;
table.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
table.TotalWidth = (image.Width - (image.Width / 3));
table.AddH1(#"شهادة", new iTextSharp.text.Font(Tajawal));
table.WriteSelectedRows(0, -1, 60, 420, cb);
document.Close();
and the Method for AddH1 is as following:
public static void AddH1(this PdfPTable table, string Text, iTextSharp.text.Font tajawal)
{
tajawal.Size = 26f;
tajawal.SetStyle(iTextSharp.text.Font.BOLD);
Phrase ph = new Phrase(Text, tajawal);
PdfPCell text = new PdfPCell(ph);
text.HorizontalAlignment = PdfPCell.ALIGN_CENTER;
text.Padding = 6;
text.Border = 0;
text.NoWrap = false;
text.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
table.AddCell(text);
}
My problem is if I use Tajawal font some of the characters are missing, like the last letter, if i use Tahoma font it works as expected, I'm thinking it might be a problem with encoding, any one faced this before ?
if i use the same font on word, or HTML it works perfectly, one thing to notice here is that Arabic letters can be presented in a separated way or joined together, what i figured out is all characters will not be displayed if typed in separated way, it would only work if its joined.
If i open Character Map i found out the following:
Characters starting from U+0621 to U+0649 are separated form (Does not work)
Characters starting from U+FE82 to U+FEFC are joined form (Works Perfectly)

Related

iTextSharp how to add Cyrillic font in PDF document

I have a previously created PDF file.
I want to add a stamp to it with Cyrillic characters and a frame.
For example
For this i use iTextSharp 5.5.13.3
I can make a rectangle, but when I want to add text, I get an error:
System.ArgumentException: 'windows-1252' is not a supported encoding
name. For information on defining a custom encoding, see the
documentation for the Encoding.RegisterProvider method. (Parameter
'name')
Code that does this:
PdfTemplate layer2 = appearance.GetLayer(2);
String text = " Копия ВЕРНА\n"
+ " Дата: " + DateTime.Now.ToString("dd.MM.yyyy HH:mm") +"\n";
string externalFont = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Fonts), "Arial.TTF");
BaseFont externalBaseFont = BaseFont.CreateFont(externalFont, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); **Throws an exception here!**
Font font = new Font(externalBaseFont,6, Font.NORMAL, BaseColor.BLACK);
float size = font.Size;
float margin = 1;
Rectangle dataRect = new Rectangle(margin, margin, appearance.Rect.Width- margin, appearance.Rect.Height - margin);
if (size <= 0)
{
Rectangle sr = new Rectangle(dataRect.Width, dataRect.Height);
size = ColumnText.FitText(font, text, sr, 10, appearance.RunDirection);
}
ColumnText ct = new ColumnText(layer2);
ct.RunDirection=(appearance.RunDirection);
ct.SetSimpleColumn(new Phrase(text, font), dataRect.Left, dataRect.Bottom, dataRect.Right, dataRect.Top, size, Element.ALIGN_LEFT);
ct.Go();
layer2.SetRGBColorStroke(0, 0, 0);
layer2.SetLineWidth(0.5);
layer2.Rectangle(dataRect.Left, dataRect.Bottom, dataRect.Width, dataRect.Height);
layer2.Stroke();
The solution to my problem was adding:
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
Encoding.GetEncoding("windows-1252");
before reading the pdf
using (PdfReader reader = new PdfReader(unsignedPdf))
{
...
}

Adding text to all page at specific position

So basically I've been trying to add a text vertically at a existing pdf. The existing pdf is in A4 and is first converted to Letter size, then I add a single text per page.
Problem is I think Im having double text per page at different positions instead of only 1 text per page.
using (PdfReader pdfr = new PdfReader(input))
{
using (Document doc = new Document(PageSize.LETTER))
{
Document.Compress = true;
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(output, FileMode.Create));
doc.Open();
PdfPTable table;
PdfPCell cell;
Paragraph paragraph;
PdfContentByte cb = writer.DirectContent;
PdfImportedPage page;
for (int i = 1; i < pdfr.NumberOfPages + 1; i++)
{
page = writer.GetImportedPage(pdfr, i);
cb.AddTemplate(page, PageSize.LETTER.Width / pdfr.GetPageSize(i).Width, 0, 0, PageSize.LETTER.Height / pdfr.GetPageSize(i).Height, 0, 0);
table = new PdfPTable(1);
table.TotalWidth = 20;
paragraph = new Paragraph("helloworld");
cell = new PdfPCell(paragraph);
cell.Rotation = 90;
cell.BorderWidth = 10;
table.AddCell(cell);
table.WriteSelectedRows(0, -1, 300f, 200f, writer.DirectContent);
doc.Add(table);
doc.NewPage();
}
doc.Close();
doc.Dispose();
}
pdfr.Dispose();
}
For some reason another table at the top most is being generated.
you must use PdfPageEventHelper. and implement this methode public override void OnEndPage(PdfWriter writer, Document document)

iTextSharp - dynamic content with a footer, using padding

I am attempting to create documents that are highly-variable in length, and make them something that can be table-driven. I am trying to use iTextSharp tables exclusively to create the documents, including footer verbiage. In the code below I’m trying to pad the very last cell to the exact amount equal to the remaining space, so that my footer will be placed exactly at the bottom of the document, tight against the bottom margin. This works fine when I try to use document margins of 1, 2, or 3 inches, but when I use 5 for example, my footer begins to wrap. I think this may simply be a case of bad math. Does anyone have any suggestions to correct this (outside of using Page Events)?
(*Note: there are 2 helper methods used in creating tables and measuring the height of a paragraph, also included in addition to the main code from a button click)
(*Note: each table has SplitLate set to false, to make the content flow from page to page evenly); all tables have a specific width, and the width is locked
//declare path for the PDF file to be created
string strpath = #"C:\CROauto\Junk\MSE.pdf";
//instantiate a new PDF document
//(regular portrait format, with half-inch margins all around)
var doc = new Document(PageSize.LETTER,
iTextSharp.text.Utilities.InchesToPoints(1f),
iTextSharp.text.Utilities.InchesToPoints(1f),
iTextSharp.text.Utilities.InchesToPoints(5f),
iTextSharp.text.Utilities.InchesToPoints(.5f));
//create a PDF table
//(2 column, with no border)
PdfPTable mas_tbl = clsPDF.CreateTable(2, false, cell_padding_bottom: 0f, total_width: doc.PageSize.Width - doc.LeftMargin - doc.RightMargin);
//get base font types
BaseFont font_tb = FontFactory.GetFont(FontFactory.TIMES_BOLD).BaseFont;
BaseFont font_t = FontFactory.GetFont(FontFactory.TIMES).BaseFont;
//create regular Font objects, with varying sizes
iTextSharp.text.Font f10 = new iTextSharp.text.Font(font_t, 10);
iTextSharp.text.Font f8 = new iTextSharp.text.Font(font_t, 8);
//create regular Font objects, bold, with varying sizes
iTextSharp.text.Font fb10 = new iTextSharp.text.Font(font_tb, 10);
iTextSharp.text.Font fb8 = new iTextSharp.text.Font(font_tb, 8);
//get image
iTextSharp.text.Image da_img = iTextSharp.text.Image.GetInstance(#"C:\CROauto\Junk\img.gif");
//scale the image to a good size
da_img.ScaleAbsolute(iTextSharp.text.Utilities.InchesToPoints(.75f),
iTextSharp.text.Utilities.InchesToPoints(.75f));
//create new PDF cell to hold image
PdfPCell icell = new PdfPCell();
icell.PaddingBottom = 0f;
//make sure the "image" cell has no border
icell.Border = iTextSharp.text.Rectangle.NO_BORDER;
//add the image to the PDF cell
icell.AddElement(da_img);
//add the image cell to the table
mas_tbl.AddCell(icell);
//work with the return address
PdfPCell ra = new PdfPCell();
ra.Border = iTextSharp.text.Rectangle.NO_BORDER;
ra.PaddingBottom = 5f;
PdfPTable tblra = clsPDF.CreateTable(1, false);
tblra.HorizontalAlignment = Element.ALIGN_RIGHT;
Chunk c = new Chunk("Help Me Please", fb8);
string rtnadd = "\r\n123 iTextSharp Rd\r\nHelpMe, ST 12345\r\n\r\nstackoverflow.com";
Phrase pra = new Phrase(rtnadd, f8);
Paragraph p = new Paragraph();
p.SetLeading(1f, 1.1f);
p.Add(c);
p.Add(pra);
tblra.TotalWidth = clsPDF.GetLongestWidth(p) + ra.PaddingLeft + ra.PaddingRight + 2;
ra.AddElement(p);
tblra.AddCell(ra);
PdfPCell dummy = new PdfPCell();
dummy.PaddingBottom = 0f;
dummy.Border = iTextSharp.text.Rectangle.NO_BORDER;
dummy.AddElement(tblra);
mas_tbl.AddCell(dummy);
//create "content" table
PdfPTable t2 = clsPDF.CreateTable(1, false, Element.ALIGN_JUSTIFIED, cell_padding_bottom: 0f);
//create FileStream for the file
using (FileStream fs = new FileStream(strpath, FileMode.Create))
{
//get an instance of a PdfWriter, attached to the FileStream
PdfWriter.GetInstance(doc, fs);
//open the document
doc.Open();
string tmp = "";
for (int i = 0; i < 80; i++)
{
tmp += "The brown fox jumped over the lazy dog a whole bunch of times." + i.ToString();
}
Phrase p2 = new Phrase(tmp, f10);
t2.AddCell(p2);
p2 = new Phrase("Another paragraph", f10);
t2.AddCell(p2);
tmp = "";
PdfPTable t3 = clsPDF.CreateTable(1, false, cell_padding_bottom: 0f);
for (int i = 0; i < 150; i++)
{
tmp += "The lazy dog didn't like that very much." + i.ToString();
}
t3.AddCell(new Phrase(tmp, f10));
t2.AddCell(t3);
t2.AddCell(new Phrase("I SURE HOPE THIS WORKED", f10));
PdfPCell c2 = new PdfPCell();
c2.PaddingBottom = 0f;
c2.Border = iTextSharp.text.Rectangle.NO_BORDER;
c2.Colspan = mas_tbl.NumberOfColumns;
c2.AddElement(t2);
mas_tbl.AddCell(c2);
//work with adding a footer
//FOOTER MSE: ADD ENOUGH PADDING TO PUSH THE FOOTER TO THE BOTTOM OF THE PAGE
Paragraph fp = new Paragraph(new Phrase("Line 1 of footer\r\nLine 2 of footer\r\nhere's more of my footer text:\r\nthis project was SOOOO much fun\r\nand stuff", fb8));
//get the height of the footer
float footer_height = clsPDF.GetTotalHeightOfParagraph(fp);
Console.WriteLine("Footer height {0}", footer_height.ToString());
//get the total amount of "writeable" space per page
//(taking top and bottom margins into consideration)
float avail = doc.PageSize.Height - (doc.TopMargin + doc.BottomMargin);
//declare a variable to assist in calculating
//the total amount of "writeable" room remaining
//on the last page;
//start with with the current height of the master table
//(will do math below to calculate just what it's using
// on the last page)
float mas_tbl_last_page_height = mas_tbl.TotalHeight;
//the purpose of this loop is to start determining
//how much writeable space is left on the last page;
//this loop will subtract the "available" value from
//the total height of the master table until what's
//left is the amount of space the master table is
//using on the last page of the document only
while (mas_tbl_last_page_height > avail)
{
mas_tbl_last_page_height -= avail;
}
//to truly calculate the amount of writeable space
//remaining, subtract the amount of space that the
//master table is utilizing on the last page of
//the document, from the total amount of writeable
//space per page
float room_remaining = avail - mas_tbl_last_page_height;
//declare variable for the padding amount
//that will be used above the footer
float pad_amt = 0f;
if (room_remaining > (footer_height * 2))
{
//pad to push down
pad_amt = room_remaining - (footer_height * 2);
}
else
{
//don't use a pad
//(just let the table wrap normally)
pad_amt = 0f;
}
//declare the footer cell, and set all of it's values
PdfPCell ftcell = new PdfPCell();
ftcell.HorizontalAlignment = Element.ALIGN_JUSTIFIED;
//(use column span that is equal to the number of
// columns in the master table)
ftcell.Colspan = mas_tbl.NumberOfColumns;
ftcell.Border = iTextSharp.text.Rectangle.NO_BORDER;
ftcell.PaddingTop = pad_amt;
ftcell.PaddingBottom = 0f;
ftcell.AddElement(fp);
//add the footer cell to the master table
mas_tbl.AddCell(ftcell);
//add the master table to the document, which should contain everything
doc.Add(mas_tbl);
//close the document
doc.Close();
//HELPER METHODS
internal static PdfPTable CreateTable(int column_count,
bool include_border,
int h_align = Element.ALIGN_LEFT,
int v_align = Element.ALIGN_TOP,
float leading_multiplier = 1.1f,
float total_width = 468f,
float cell_padding_bottom = 5f,
float cell_padding_top = 0)
{
////////////////////////////////////////////////////////////////////////////////////
PdfPTable t = new PdfPTable(column_count);
//this line will keep the inner tables,
//from splitting off onto a 2nd page
//(making them only do it on wrapping)
//*NOTE: this needs to be tested thoroughly
// to make sure that rows aren't dropped!!!
t.SplitLate = false;
//used if you're adding paragraphs directly to table cells,
//instead of adding new PdfPCell objects
if (include_border == false)
{
t.DefaultCell.Border = Rectangle.NO_BORDER;
}
t.DefaultCell.PaddingLeft = 0f;
t.DefaultCell.PaddingRight = 0f;
t.DefaultCell.PaddingTop = cell_padding_top;
t.DefaultCell.PaddingBottom = cell_padding_bottom;
t.DefaultCell.HorizontalAlignment = h_align;
t.DefaultCell.VerticalAlignment = h_align;
t.TotalWidth = total_width;
t.LockedWidth = true;
t.DefaultCell.SetLeading(0, leading_multiplier);
return t;
}
internal static float GetLongestWidth(Paragraph p)
{
List<float> f = new List<float>();
foreach (Chunk c in p.Chunks)
{
string[] strarray = c.Content.Split(new string[] { "\r\n" }, System.StringSplitOptions.None);
for (int i = 0; i < strarray.Length; i++)
{
Chunk tc = new Chunk(strarray[i], c.Font);
Console.WriteLine(tc.Content + ", width: {0}", tc.GetWidthPoint().ToString());
f.Add(tc.GetWidthPoint());
}
}
return f.Max();
}
internal static float GetTotalHeightOfParagraph(Paragraph p)
{
PdfPTable t = clsPDF.CreateTable(1, false, cell_padding_bottom: 0f);
t.DefaultCell.PaddingBottom = 0f;
t.DefaultCell.PaddingTop = 0f;
t.AddCell(p);
return t.TotalHeight;
}
Solved it by using absolute positioning. I calculate the position that the footer should be in, by adding the footer height to the value of the bottom margin. To alleviate concerns about overwriting existing content, I calculate the amount of available space remaining on the last page; if it's not enough for my footer, I add a new page and post my content at the beginning of the next page.
byte[] content;
using (MemoryStream output = new MemoryStream())
{
PdfReader pdf_rdr = new PdfReader(strpath);
PdfStamper stamper = new PdfStamper(pdf_rdr, output);
PdfContentByte pcb = stamper.GetOverContent(pdf_rdr.NumberOfPages);
PdfPTable ftbl = clsPDF.CreateTable(1, false, cell_padding_bottom: 0f);
Paragraph fp = new Paragraph(new Phrase("Line 1 of footer\r\nLine 2 of footer\r\nhere's more of my footer text:\r\nthis project was SOOOO much fun\r\nand stuff", fb8));
//get the height of the footer
float footer_height = clsPDF.GetTotalHeightOfParagraph(fp);
Console.WriteLine("Footer height {0}", footer_height.ToString());
//get the total amount of "writeable" space per page
//(taking top and bottom margins into consideration)
float avail = doc.PageSize.Height - (doc.TopMargin + doc.BottomMargin);
//declare a variable to assist in calculating
//the total amount of "writeable" room remaining
//on the last page;
//start with with the current height of the master table
//(will do math below to calculate just what it's using
// on the last page)
float mas_tbl_last_page_height = mas_tbl.TotalHeight;
mas_tbl_last_page_height = mas_tbl_last_page_height % avail;
avail = avail - mas_tbl_last_page_height;
Console.WriteLine(clsPDF.GetTotalHeightOfParagraph(fp).ToString());
//float ft_top = avail - mas_tbl_last_page_height - clsPDF.GetTotalHeightOfParagraph(fp) - doc.BottomMargin;
float ft_top = doc.BottomMargin + clsPDF.GetTotalHeightOfParagraph(fp);
ftbl.AddCell(fp);
if (avail < clsPDF.GetTotalHeightOfParagraph(fp))
{
stamper.InsertPage(pdf_rdr.NumberOfPages + 1, pdf_rdr.GetPageSize(1));
pcb = stamper.GetOverContent(pdf_rdr.NumberOfPages);
ft_top = doc.PageSize.Height - doc.TopMargin;
}
ftbl.WriteSelectedRows(0, -1, doc.LeftMargin, ft_top, pcb);
// Set the flattening flag to true, as the editing is done
stamper.FormFlattening = true;
// close the pdf stamper
stamper.Close();
//close the PDF reader
pdf_rdr.Close();
content = output.ToArray();
}
//write the content to a PDF file
using (FileStream fs = File.Create(strpath))
{
fs.Write(content, 0, (int)content.Length);
fs.Flush();
}

Unable to vertically align text in table cell with itextsharp

I can not figure out how to vertically align text in table cell. horizontal alignment is ok. I use itextsharp to generate pdf. Alignment should be applied to cells in table kitosKalbosTable. Any help would be appreciated. here's my code:
var table = new PdfPTable(new float[]
{
36, 1, 63
});
table.WidthPercentage = 100.0f;
table.HorizontalAlignment = Element.ALIGN_LEFT;
table.DefaultCell.Border = Rectangle.NO_BORDER;
table.SplitRows = false;
.........
PdfPTable kitosKalbosTable = new PdfPTable(new float[] {10, 30});
kitosKalbosTable.TotalWidth = 40f;
kitosKalbosTable.SplitRows = false;
kitosKalbosTable.AddCell("Kalba", FontType.SmallTimes, vAligment: Element.ALIGN_MIDDLE, hAligment: Element.ALIGN_CENTER);
..........
table.AddCell(kitosKalbosTable);
//method in other file
public static PdfPCell CreateCell(
string text,
FontType? fontType = FontType.RegularTimes,
int? rotation = null,
int? colspan = null,
int? rowspan = null,
int? hAligment = null,
int? vAligment = null,
int? height = null,
int? border = null,
int[] disableBorders = null,
int? paddinLeft = null,
int? paddingRight = null,
bool? splitLate = null)
{
var cell = new PdfPCell();
............
if (vAligment.HasValue)
{
cell.VerticalAlignment = vAligment.Value;
}
return cell;
}
You have a complex example that appears to be using nested tables and extension methods. As Alexis pointed out, the VerticalAlignment is the correct property to use. Below is a full working example of this. I recommend getting rid of your extension method for now and just starting with this example.
//Our test file to output
var testFile = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
//Standard PDF setup, nothing special here
using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
using (var doc = new Document()) {
using (var writer = PdfWriter.GetInstance(doc, fs)) {
doc.Open();
//Create our outer table with two columns
var outerTable = new PdfPTable(2);
//Create our inner table with just a single column
var innerTable = new PdfPTable(1);
//Add a middle-align cell to the new table
var innerTableCell = new PdfPCell(new Phrase("Inner"));
innerTableCell.VerticalAlignment = Element.ALIGN_MIDDLE;
innerTable.AddCell(innerTableCell);
//Add the inner table to the outer table
outerTable.AddCell(innerTable);
//Create and add a vertically longer second cell to the outer table
var outerTableCell = new PdfPCell(new Phrase("Hello\nWorld\nHello\nWorld"));
outerTable.AddCell(outerTableCell);
//Add the table to the document
doc.Add(outerTable);
doc.Close();
}
}
}
This code produces this PDF:
Use
cell.VerticalAlignment = Element.ALIGN_MIDDLE; // or ALIGN_TOP or ALIGN_BOTTOM
Also, you can set a default vertical alignment for all cells by setting
kitosKalbosTable.DefaultCell.VerticalAlignment
It seems Element.ALIGN_MIDDLE only works, when the cell height is large i.r.t the text height.
In a PDF, margins for text in cells are large by default, see iText developers
You could append a \n and a space to your string to solve this, but the cell height will become much larger.
For normal text, one way to lift text in a chunk a few pixels is:
myChunk.SetTextRise(value);
Only drawback: when the text is underlined (like a link) it only raises the text ! not the underline..
The following seems to work for underlined text also,
myCell.PaddingBottom = value;
The idea was to put a link in a table cell.. blue font, underlined, vertical centering.
My code now:
iTextSharp.text.Font linksFont =
FontFactory.GetFont(FontFactory.HELVETICA,
10, Font.UNDERLINE, BaseColor.BLUE);
PdfPTable myTable = new PdfPTable(1);
Chunk pt = new Chunk("Go Google Dutch", linksFont);
pt.SetAnchor(new Uri("https://www.google.nl"));
Phrase ph1 = new Phrase(pt);
PdfPCell cellP = new PdfPCell();
cellP.PaddingBottom = linksFont.CalculatedSize/2;
cellP.AddElement(ph1);
myTable.AddCell(cellP);

Image auto resizes in PdfPCell with iTextSharp

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

Categories

Resources