Monday, March 5, 2012

Combine image and text in a PdfPCell

Hey all,

Was confused as to how to combine an image and text together in ASP.net C#, while using the iTextSharp PDF library. Googled a bit and found my answer.

I'm not an expert at this so I'll just list out the code that would be understandable for dabblers.

If it's too long for you to read (including my babbling), just scroll down to the code

Starting off, I use a [Document] to contain a [PdfPTable] that holds [PdfPCell]s.
Being new to this I was hard-wired to think, 1 PdfPCell, 1 item, with that item being maybe text, or just graphics alone.

However I got stumped when I was required to c
ombine text and graphics together in a cell due to formatting, like wanting to have an image next to a label. I tried two separate cells with the image aligned to the right, and text aligned to the right (I needed it to the end) but due to the Colspan and width properties, I got this.


Yeah, you see it right? I needed that round image next to the text, however due to each cell being 100 pixels and the label not using up all the space I had this ugly effect.

Now here's what you were for! A cell can have multiple elements in there.
A quick touchdown on the solution. Remember
PdfPCell? It used to hold one item, either an Image, or a Phrase or Paragraph.

But now, [PdfPcell] holds 1 [Paragraph], which holds 1 [Chunk] (image) and 1 [Phrase] (text). So I get this!
Further formatting can be done with the X and Y offset to shift the image, you'll see it in the code as (image, 0, 0).

Now here's the code:

Document doc = new Document();

doc.Open();

PdfPTable table = new PdfPTable(5);
table.TotalWidth = 500f;
table.LockedWidth = true;

...
Paragraph paragraph = new Paragraph();
paragraph .Add(new Chunk(image, 0, 0)); // x y offsets as 0 but you can edit it in your code to align the image

paragraph.Add(new Phrase("Admin CP J", timesSmallBlack));
paragraph.Alignment = 2; // This alignment affects the positioning within the cell, important!

PdfPCell cell = new PdfPCell(paragraph );
cell.Colspan = 3;
cell.HorizontalAlignment = 2; //0=Left, 1=Centre, 2=Right
cell.Border = 0;
table.AddCell(cell);

...

doc.Add(table);

Now, kudos to the original post which I've found: How to get a gif in a pdfpcell to line up with trailing text

If you enjoyed my post and it has helped you and you would like to return the favour you can click any of the sponsored Google ads around the page, thank you!

No comments:

Post a Comment