使用ItextSharp在PDF中绘制图像上的线条 [英] Draw Lines on Image in PDF using ItextSharp

查看:1206
本文介绍了使用ItextSharp在PDF中绘制图像上的线条的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在需要加载到pdf文档上的图像上绘制线条,就像我们在任何控件的paint事件上绘制图形一样,但它没有这样做。

I am trying to draw lines on image that needs to be loaded on pdf document, just like we draw graphics on paint event of any control, but it fails to do so.

任何建议?

Document pdfDoc = new Document(PageSize.A2, 10f, 10f, 10f, 0f);
pdfDoc.AddHeader("Batting Report - ", txtSearchBox.Text);

iTextSharp.text.Image pic = iTextSharp.text.Image.GetInstance(Properties.Resources.bgWW
                        , System.Drawing.Imaging.ImageFormat.Jpeg);


PdfWriter writer = PdfWriter.GetInstance(pdfDoc, stream);
pdfDoc.Open();

pdfDoc.Add(pic);

那么,如何修改ItextSharpImage的pic对象以便它可以在图像上绘制线条?

So, how do I modify the pic object of ItextSharpImage so that it can draw lines on the image?

推荐答案

请看一下 WatermarkedImages4 示例。它基于我在评论中提到的 WatermarkedImages1 示例。两个示例之间唯一不同的是我们在回答如何向图像添加文本?​​
而我们在回答您的问题的示例中添加行。

Please take a look at the WatermarkedImages4 example. It is based on the WatermarkedImages1 example I referred to in the comments. The only different between the two examples is that we add text in the example written in answer to How to add text to an image? whereas we add lines in the example written in answer to your question.

我们添加图像这个:

document.add(getWatermarkedImage(cb, Image.getInstance(IMAGE1)));

getWatermarkedImage()方法如下所示:

public Image getWatermarkedImage(PdfContentByte cb, Image img) throws DocumentException {
    float width = img.getScaledWidth();
    float height = img.getScaledHeight();
    PdfTemplate template = cb.createTemplate(width, height);
    template.addImage(img, width, 0, 0, height, 0, 0);
    template.saveState();
    template.setColorStroke(BaseColor.GREEN);
    template.setLineWidth(3);
    template.moveTo(width * .25f, height * .25f);
    template.lineTo(width * .75f, height * .75f);
    template.moveTo(width * .25f, height * .75f);
    template.lineTo(width * .25f, height * .25f);
    template.stroke();
    template.setColorStroke(BaseColor.WHITE);
    template.ellipse(0, 0, width, height);
    template.stroke();
    template.restoreState();
    return Image.getInstance(template);
}

如您所见,我使用 moveTo(), lineTo() stroke()。我还使用 ellipse() stroke()方法添加一个白色椭圆。

As you can see, I add two green lines using moveTo(), lineTo() and stroke(). I also add a white ellipse using the ellipse() and stroke() method.

这导致PDF如下所示:

This results in a PDF that looks like this:

如您所见,椭圆的形状和线条的位置因不同的图像而不同因为我根据图像的宽度和高度定义了我的坐标。

As you can see, the shape of the ellipse and the position of the lines are different for the different images because I defined my coordinates based on the width and the height of the image.

这篇关于使用ItextSharp在PDF中绘制图像上的线条的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆