Skip to main content
Skip table of contents

How to set the line width of a clipping path?

How do I change the size of my clipping path?

I have a PdfTemplate and I want to clip its shape to a specific path. I know how to do this, but the clipping line is always the same (probably 1 px) and I want to be able to change it. Is there any way to do this?

This is my code:

 

PdfTemplate template = contentByte.CreateTemplate(100, 200);
template.MoveTo(0, 0);
template.LineTo(50, 50);
template.LineTo(50, 0);
template.LineTo(0, 50);
template.SetLineWidth(5);
template.Clip();
Image img = Image.getInstance(RESOURCE);
template.Add(img, 0, 0);
SetLineWidth() doesn't work.

 

Posted on StackOverflow on Sep 28, 2015 by Piotr M

Take a note that in iText 7 we use the different approach to work with PdfContentByte and PdfTemplate. There are PdfFormXObject and PdfCanvas classes that help you.

Problem #1: You never stroke the path, hence it is never drawn. First try this:

PdfFormXObject xObject = new PdfFormXObject(new Rectangle(100, 200));
PdfCanvas canvas = new PdfCanvas(xObject, pdfDoc);
canvas.moveTo(0, 0);
canvas.lineTo(50, 50);
canvas.lineTo(50, 0);
canvas.lineTo(0, 50);
canvas.setLineWidth(5);
canvas.clip();
canvas.addImage(img, 0, 0, width, true);
canvas.stroke();

Problem #2: You are using your clipping path for two different purposes.

  1. To cut out a shape when adding an Image.

  2. To draw the path.

That doesn't look right. I'm not sure if every PDF viewer will actually stroke that path as you clearly use that path to clip content.

I would write this code like this:

PdfFormXObject xObject = new PdfFormXObject(new Rectangle(100, 200));
PdfCanvas canvas = new PdfCanvas(xObject, pdfDoc);
canvas.moveTo(0, 0);
canvas.lineTo(50, 50);
canvas.lineTo(50, 0);
canvas.lineTo(0, 50);
canvas.clip();
canvas.newPath();
canvas.addImage(img, 0, 0, width, true);
canvas.moveTo(0, 0);
canvas.lineTo(50, 50);
canvas.lineTo(50, 0);
canvas.lineTo(0, 50);
canvas.setLineWidth(5);
canvas.stroke();

The first time, you use the path as a clipping path. It doesn't make sense to define a line width for a clipping path: the path defines the shape that needs to be cut out.

The second time, you use the path to stroke the borders of a shape. The lines that make these borders have a width. Note that you're only drawing three lines. You may want to close the path!

P.S. In this code snippet we define the image like this:

ImageData img = ImageDataFactory.create(imgSrc);
Image imgModel = new Image(img);
float width = imgModel.getImageScaledWidth();

Click How to set the line width of a clipping path? if you want to see how to answer this question in iText 5.

JavaScript errors detected

Please note, these errors can depend on your browser setup.

If this problem persists, please contact our support.