Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iTextSharp Scaling image to be full-page

I'm trying to scale an image to be full-page on a PDF document. I'm generating the document using iTextSharp. The image has the correct aspect ratio for the page but I'd ideally prefer that the image distort rather than not fill all available area.

I currently have:

Dim Document As New Document(PageSize, 0, 0, 0, 0)
...
Dim ContentImage = '''Method call to get image'
Dim Content = iTextSharp.text.Image.GetInstance(ContentImage, New BackgroundColor)
Content.SetAbsolutePosition(0, 0)
Content.ScaleToFit(Document.PageSize.Width, Document.PageSize.Height)
Document.Add(Content)

Unfortunately, this doesn't account for printer margins...

I need the image to fit the printable area (as best as can be defined in a pdf)

Thanks in advance

like image 252
Basic Avatar asked Feb 08 '11 10:02

Basic


2 Answers

If you're determined to do it empirically, then take print a page with your code as is that scales to page border such that the image would paint black in the first half inch of margin, if it could go to the edge. Measure the distance from each edge to black in inches and divide each by 72.0.

Let's name them: lm, rm, tm, bm (left right top bottom margins.

Dim pageWidth = document.PageSize.Width - (lm + rm);
Dim pageHeight = document.PageSize.Height - (bm + tm);
Content.SetAbsolutePosition(lm, bm);
Content.ScaleToFit(pageWidth, pageHeight);
Document.Add(Content)
like image 82
plinth Avatar answered Oct 16 '22 14:10

plinth


You can scale an image to fit the PDF page by using following code snippet.

VB

Dim img As iTextSharp.text.Image = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromStream(resourceStream), System.Drawing.Imaging.ImageFormat.Png)
img.SetAbsolutePosition(0, 0) 
'set the position to bottom left corner of pdf
img.ScaleAbsolute(iTextSharp.text.PageSize.A7.Width, iTextSharp.text.PageSize.A7.Height)
'set the height and width of image to PDF page size

C#

iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(System.Drawing.Image.FromStream(resourceStream, System.Drawing.Imaging.ImageFormat.Png);
img.SetAbsolutePosition(0, 0); // set the position to bottom left corner of pdf
img.ScaleAbsolute(iTextSharp.text.PageSize.A7.Width,iTextSharp.text.PageSize.A7.Height); // set the height and width of image to PDF page size

If you want the full code(c#) you can refer the following link also. The full code add image to all pages of an existing PDF.

https://stackoverflow.com/a/45486484/6597375

like image 42
Deepu Reghunath Avatar answered Oct 16 '22 14:10

Deepu Reghunath