【问题标题】:center image in pdf using itextsharp使用itextsharp在pdf中居中图像
【发布时间】:2016-08-26 07:43:33
【问题描述】:

我在这里要做的是将图像添加到空白 pdf 中。到目前为止,我已经完成了,但我希望图像居中。我怎样才能做到这一点?

这是我的 C# 代码:

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();
}

这是输出:

https://drive.google.com/open?id=0BzaejXGgqBOAMzd0UlY2QWFXNms

我想要的是图像在页面上居中。目前图像位于页面顶部。

我什至设置了图像对齐,但为什么它不在页面上居中?

【问题讨论】:

    标签: c# itext


    【解决方案1】:

    您需要使用SetAbsolutePosition() 来使图像居中。

    在调用doc.Add(image1);之前,只需将以下内容添加到您的代码中:

    ...
    ...
    
    image1.SetAbsolutePosition((PageSize.A4.Width - image1.ScaledWidth) / 2, (PageSize.A4.Height - image1.ScaledHeight) / 2);
    
    doc.Add(image1);
    
    ...
    ...
    

    希望这会有所帮助。

    【讨论】:

    • 很高兴 :)
    • 如何将旋转 90 度的图像居中?
    猜你喜欢
    • 1970-01-01
    • 2011-08-22
    • 2015-06-23
    • 1970-01-01
    • 1970-01-01
    • 2011-11-27
    • 1970-01-01
    • 1970-01-01
    • 2016-04-24
    相关资源
    最近更新 更多