ItextSharp如何在页面中央添加图片并在其下方添加文本

3

我试图在带有文字的PDF文件中将图片居中添加到页面上,但是我无法正确地实现它。我使用SetAbsolutePosition设置图像位置,但是文字不会出现在图片下面。

我需要在我的PDF文件中按照以下格式显示页面:

enter image description here

我使用了如下代码:

                PdfWriter writer = PdfWriter.GetInstance(doc, fs);

                ITextEvents ev = new ITextEvents();
                writer.PageEvent = ev;
                doc.Open();

                var paragraph = new Paragraph();
                var paragraph1 = new Paragraph();
                var chunk = new Chunk("Text under picture", f14nb);
                var chunk1 = new Chunk("Code of picture", f14);

                img = ScaleImg(Image.GetInstance(imgNane_2));
                img.SetAbsolutePosition((PageSize.A4.Width - img.ScaledWidth) / 2,
                    ((PageSize.A4.Height - img.ScaledHeight) / 2));
                
                paragraph.Add(img);
                paragraph1.Add(chunk);
                paragraph1.Add(chunk1);
                doc.Add(paragraph);
                doc.Add(paragraph1);
                
                doc.Close();

private Image ScaleImg(Image img)
{
    if (img.Height > img.Width)
    {
        //Maximum height is 800 pixels.
        float percentage = 0.0f;
        percentage = 640 / img.Height;
        img.ScalePercent(percentage * 100);
    }
    else
    {
        //Maximum width is 600 pixels.
        float percentage = 0.0f;
        percentage = 500 / img.Width;
        img.ScalePercent(percentage * 100);
    }
    return img;
}

我认为我应该使用另一种方法来解决我的问题,但我不知道应该选择哪一种。
谢谢。
1个回答

0

我明白如何做了。

这是用于带有文本的图像:

        public Image getWatermarkedImage(Document Doc, Image img, String watermarkText)
    {
        float width = img.ScaledWidth;
        float height = img.ScaledHeight;

        PdfTemplate template = cb.CreateTemplate(width, height);

        template.AddImage(img, width, 0, 0, height, 0, 0);
        ColumnText.ShowTextAligned(template, Element.ALIGN_RIGHT,
            new Phrase(watermarkText, fontBold_14), width - 10, 10, 0);

        return Image.GetInstance(template);
    }

这是用于在图像下方添加文本(主代码):

                var codeOfPicture = "*Code of picture* - *Код картинки*";

                var chunk = new Chunk("Text under picture", font_14);

                img = ScaleImg(Image.GetInstance(imgNane_1));//imgNane_2));

                var tmpImg = getWatermarkedImage(doc, img, codeOfPicture);
                var textY = ((PageSize.A4.Height - img.ScaledHeight) / 2) - 15;
                var textX = PageSize.A4.Width / 2;

                tmpImg.SetAbsolutePosition((PageSize.A4.Width - img.ScaledWidth) / 2,
                    ((PageSize.A4.Height - img.ScaledHeight) / 2));

                doc.Add(tmpImg);

                ColumnText.ShowTextAligned(cb, Element.ALIGN_CENTER, new Phrase(chunk), textX, textY, 0);

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接