简体   繁体   中英

center image in pdf using itextsharp

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM