You are on page 1of 4

iTextSharp " #orking with images

http(99www.mikesdotnetting.com9Article9=09iTextSharp"...

iTextSharp - Working with images


The seventh article in my iTextSharp series looks at working with images. This article builds on the previous six which are listed below. Create PDFs in ASP. !T " getting started with iTextSharp iTextSharp " #orking with Fonts iTextSharp " Adding Text with Chunks$ Phrases and Paragraphs %ists with iTextSharp iTextSharp " %inks and &ookmarks iTextSharp " 'ntroducing Tables iTextSharp supports all the main image types( )pg$ ti*$ gi*$ bmp$ png and wm*. There are a number o* ways to create images with iTextSharp using the Image.GetInstance() method. Probably the most used option will be to pass a *ilesystem path and *ile name into the method(
string pdfpath = Server.MapPath("PDFs"); string imagepath = Server.MapPath("Images"); Document doc = new Document(); try { PdfWriter.GetInstance(doc, new FileStream(pdfpath + "/Images.pdf", FileMode.Create)); doc.Open(); doc.Add(new Paragraph("GIF")); Image gif = Image.GetInstance(imagepath + "/mikesdotnetting.gif"); doc.Add(gif); } catch (Exception ex) { //Log error; } finally { doc.Close(); }

Alternative constructors that you may use include passing a +,% or a System.Drawing.Image ob)ect -as opposed to an iTextSharp.text.Image.. ote " the *ollowing snippet that System.Drawing.Image.FromStream() method shows the use o* namespace aliasing again (sd.Image.FromStream(fs).$ as was highlighted in the article %ists with iTextSharp to avoid clashes with the two di**erent types o* Image ob)ect(
doc.Add(new Paragraph("JPG")); string url = "http://localhost:1805/PDF/Images/mikesdotnetting.jpg"; Image jpg = Image.GetInstance(new Uri(url)); doc.Add(jpg); doc.Add(new Paragraph("PNG")); using (FileStream fs = new FileStream(imagepath + "/mikesdotnetting.png", FileMode.Open)) { Image png = Image.GetInstance(sd.Image.FromStream(fs),ImageFormat.Png); doc.Add(png); }

't/s di**icult to tell *rom the images ' have provided so *ar$ but the resolution o* the resulting images in the PDF *ile is not that great. &y de*ault$ images are embedded at 01 dpi -Dots Per 'nch. which coincidentally$ matches the number o* points in an inch. '* this *ile was being prepared *or printing$ the *inal )ob would be a bit nasty. 2enerally$ commercial printers re3uire that colour images *or printing have a resolution o* 455 dpi. To achieve this$ you can scale the image to 167. #hat you are actually trying to do is s3uee8e 455 pixels into the space that 01 normally occupies. 019455 : ;55 < 167. The image stays the same in terms o* *ile si8e but occupies less space in the document.

; o* 6

1915915;6 4(4= A>

iTextSharp " #orking with images


doc.Add(new Paragraph("TIF Scaled to 300dpi")); Image tif = Image.GetInstance(imagepath + "/mikesdotnetting.tif"); tif.ScalePercent(24f); doc.Add(tif);

http(99www.mikesdotnetting.com9Article9=09iTextSharp"...

ow$ ' have a large ti* *ile that ' want to use as a logo on an A6 letterhead. 't measures 455 x =?5 pixels. So at the de*ault 01 dpi$ it will measure 6.;0 inches wide by;1.4@ inches deep. 'ncreasing the resolution to 455 dpi will reduce the width to ; inch$ and the depth to 1.?0 inches -01 points by 1;4.@ points.. That part is *ine. #e can do that using the code above. ow ' want to place the 455 dpi image in a particular position on the page. ' have in mind the top right hand corner. The SetAbsolutePosition-. method will do this$ but ' need to get a calculator out. SetAbsolutePosition-. accepts 1 *loats as parameters. The *irst represents the co"ordinate along the A"axis$ which starts at the le*t hand edge o* the document and *inishes at the right hand edge o* the document. The second represents the B"axis co"ordinate which starts *rom the bottom o* the document and goes to the top. An A6 document is C?C points wide and =61 pixels high with a 4@ point margin all around by de*ault. The actual co"ordinate that needs to be passed in is the bottom le*t o* the image position. This image will butt right up to the right"hand margin. The image is 01 points wide -; inch. D the margin at 4@ points -total ;5= points. *rom the right hand edge o* the document$ or C?C " ;5= < 6=0 points along the A"axis. The B"axis co"ordinate is the height o* the image D the margin away *rom the top o* the document$ or =61 " -1;4.@ D 4@. < C?1.6 points *rom the bottom. Cripes. ' don/t really want to have to remember all the various si8es o* di**erent documents and do these calculations every time ' want to set the absolute position o* an element. And *ortunately$ ' don/t have to. ' can use the Document.PageSi8e ob)ect to do the work *or me.
Image tif = Image.GetInstance(imagepath + "/verticallogo.tif"); tif.ScalePercent(24f); tif.SetAbsolutePosition(doc.PageSize.Width - 36f - 72f, doc.PageSize.Height - 36f - 216.6f); doc.Add(tif);

doc.PageSi8e.#idth gives me the width in points o* the document$ and ' )ust remove the margin -4@ points. and the width o* the image -01 points. *or the A"axis co"ordinate$ and the margin and height o* the image *rom the total height o* the document *or the B"axis co"ordinate.

2ot my company logo in (". Another scenario that might need to be catered *or is to *it a user"supplied image into a *ixed si8e box somewhere on a *orm. '/ve pinched the Sunset image that ' *ound in the Sample 'mages *older in >y Pictures that comes as part o* the de*ault install o* #indowsAP to illustrate how to use the ScaleToFit-. method to achieve this. The *ollowing code takes an image o* =55 x @55 and *orces it to resi8e$ maintaining its aspect ratio$ into a rectangle measuring 1C5 points s3uare.
Image jpg = Image.GetInstance(imagepath + "/Sunset.jpg"); jpg.ScaleToFit(250f, 250f); jpg.Border = Rectangle.BOX; jpg.BorderColor = Color.YELLOW; jpg.BorderWidth = 5f; doc.Add(jpg); doc.Add(new Paragraph("Original Width: " + jpg.Width.ToString())); doc.Add(new Paragraph("Original Height " + jpg.Height.ToString())); doc.Add(new Paragraph("Scaled Width: " + jpg.ScaledWidth.ToString())); doc.Add(new Paragraph("Scaled Height " + jpg.ScaledHeight.ToString())); float Resolution = jpg.Width / jpg.ScaledWidth * 72f; doc.Add(new Paragraph("Resolution: " + Resolution));

' have also taken the opportunity to add a yellow border to the embedded image$ which is C points wide$ and then shown the original dimensions$ *ollowed by the scaled dimensions$ and the resulting resolution o* the image. And here/s the result(

1 o* 6

1915915;6 4(4= A>

iTextSharp " #orking with images

http(99www.mikesdotnetting.com9Article9=09iTextSharp"...

'* you use SetAbsolutePosition-. you end up with the same e**ect as i* you had set the Alignment property o* the image to 'mage.UNDERLYING$ in that text added to the document will run over the top o* it. +nless you want to achieve this kind o* watermark e**ect$ you need to use 'mage.TEXTWRAP instead.
Image jpg = Image.GetInstance(imagepath + "/Sunset.jpg"); Paragraph paragraph = new Paragraph(@"Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Suspendisse blandit blandit turpis. Nam in lectus ut dolor consectetuer bibendum. Morbi neque ipsum, laoreet id; dignissim et, viverra id, mauris. Nulla mauris elit, consectetuer sit amet, accumsan eget, congue ac, libero. Vivamus suscipit. Nunc dignissim consectetuer lectus. Fusce elit nisi; commodo non, facilisis quis, hendrerit eu, dolor? Suspendisse eleifend nisi ut magna. Phasellus id lectus! Vivamus laoreet enim et dolor. Integer arcu mauris, ultricies vel, porta quis, venenatis at, libero. Donec nibh est, adipiscing et, ullamcorper vitae, placerat at, diam. Integer ac turpis vel ligula rutrum auctor! Morbi egestas erat sit amet diam. Ut ut ipsum? Aliquam non sem. Nulla risus eros, mollis quis, blandit ut; luctus eget, urna. Vestibulum vestibulum dapibus erat. Proin egestas leo a metus?"); paragraph.Alignment = Element.ALIGN_JUSTIFIED; jpg.ScaleToFit(250f, 250f); jpg.Alignment = Image.TEXTWRAP | Image.ALIGN_RIGHT; jpg.IndentationLeft = 9f; jpg.SpacingAfter = 9f; jpg.BorderWidthTop = 36f; jpg.BorderColorTop = Color.WHITE; doc.Add(jpg); doc.Add(paragraph);

'n this instance$ ' added a white border to the image to align it with the top o* the text$ and a bit o* padding to the le*t and bottom o* the image to stop the text running right up to its edge. %e*t and ,ight padding can be added using the 'ndentation%e*t and 'ndentation,ight properties$ while Spacing&e*ore and SpacingA*ter is used to pad the top and bottom. Bou may ask why ' didn/t use Sapcing&e*ore instead o* adding a white border$ and that/s a good 3uestion. The *act is that whatever ' set the value to *or Spacing&e*ore$ it seemed to have no e**ect whatsover in this instance. ' have no idea why this should be$ but i* anyone does$ '/ll be pleased to hear *rom them. Ene *inal thing with images " you can rotate them i* you need to. Ene way to do this is to set the ,otation property$ which takes a *loat. The *loat value represents an angle measured in ,adians. '* you did more >athematics than ' did at school$ you may be com*ortable with this$ but i* you are like me and ask F#hatGGF$ you can either read this article on ,adians and work out that a 3uarter turn -?5H. is Pi 9 1$ or simply set the ,otationDegrees property instead. ,otation by de*ault is anti"clockwise. The *ollowing are e3ually valid and e3uivalent(
jpg.Rotation = (float)Math.PI / 2; jpg.RotationDegrees = 90f;

You might also like


iTextSharp " Drawing shapes and 2raphics iTextSharp " Page %ayout with Columns >icroso*t Chart Controls to PDF with iTextSharp and ASP. !T >IC !xporting The ,a8or #eb2rid To PDF +sing iTextSharp iTextSharp " Adding Text with Chunks$ Phrases and Paragraphs %ists with iTextSharp iTextSharp " %inks and &ookmarks iTextSharp " 'ntroducing Tables Create PDFs in ASP. !T " getting started with iTextSharp iTextSharp " #orking with Fonts

Tweet

Date Posted( Friday$ ovember 0$ 155= ;;(55 P> %ast +pdated( #ednesday$ June 15$ 15;1 6(46 P> Posted by( >ikesdotnetting Total Iiews to date( 141=?5

4 o* 6

1915915;6 4(4= A>

iTextSharp " #orking with images

http(99www.mikesdotnetting.com9Article9=09iTextSharp"...

K>ike &rind 155@ " 15;6. All rights reserved.

6 o* 6

1915915;6 4(4= A>

You might also like