简体   繁体   English

使用ItextSharp在PDF中绘制图像上的线条

[英]Draw Lines on Image in PDF using ItextSharp

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. 我试图在需要加载到pdf文档上的图像上绘制线条,就像我们在任何控件的绘制事件上绘制图形一样,但它没有这样做。

Any Suggestions ? 有什么建议么 ?

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

So, how do I modify the pic object of ItextSharpImage so that it can draw lines on the image? 那么,如何修改ItextSharpImage的pic对象,以便它可以在图像上绘制线条?

Please take a look at the WatermarkedImages4 example. 请查看WatermarkedImages4示例。 It is based on the WatermarkedImages1 example I referred to in the comments. 它基于我在评论中提到的WatermarkedImages1示例。 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. 而我们在回答你的问题时写的例子中添加了一些行。

We add images like this: 我们添加这样的图像:

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

The getWatermarkedImage() method looks like this: 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);
}

As you can see, I add two green lines using moveTo() , lineTo() and stroke() . 如您所见,我使用moveTo()lineTo()stroke()添加两条绿线。 I also add a white ellipse using the ellipse() and stroke() method. 我还使用ellipse()stroke()方法添加了一个白色椭圆。

This results in a PDF that looks like this: 这导致PDF看起来像这样:

在此输入图像描述

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. 如您所见,椭圆的形状和线条的位置因不同的图像而不同,因为我根据图像的宽度和高度定义了我的坐标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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