What I'm trying to do here is to add an image to a blank pdf. So far I've done it, but I want the image to be centered. How can I do this?
Here is my C# code:
using (MemoryStream ms = new MemoryStream())
{
Document doc = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(System.IO.Path.Combine(filepath, strFilename), FileMode.Create));
doc.AddTitle("Document Title");
doc.Open();
iTextSharp.text.Image image1 = iTextSharp.text.Image.GetInstance(@"C:\Users\Desktop\Winniethepooh.png");
image1.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
if (image1.Height > image1.Width)
{
//Maximum height is 800 pixels.
float percentage = 0.0f;
percentage = 700 / image1.Height;
image1.ScalePercent(percentage * 100);
}
else
{
//Maximum width is 600 pixels.
float percentage = 0.0f;
percentage = 540 / image1.Width;
image1.ScalePercent(percentage * 100);
}
//image1.Alignment = iTextSharp.text.Image.ALIGN_CENTER;
doc.Add(image1);
doc.Close();
}
And this is the output:
https://drive.google.com/open?id=0BzaejXGgqBOAMzd0UlY2QWFXNms
What I want is that the image is centered on the page. Currently the image is on the top of the page.
I even set the image alignment, but why doesn't it center the image on the page?
You need to use SetAbsolutePosition()
in order to center the image.
Just add the following to your code before you call doc.Add(image1);
:
...
...
image1.SetAbsolutePosition((PageSize.A4.Width - image1.ScaledWidth) / 2, (PageSize.A4.Height - image1.ScaledHeight) / 2);
doc.Add(image1);
...
...
Hope this helps.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With