简体   繁体   中英

Tile an image in PDF using iText7

I would like to be able to fill graphics objects using the tiling pattern functionality that pdf offers. For example, I would like to be able to draw something like this:

在此处输入图像描述

iText7 has a few objects related to patterns that could be useful, but I am having trouble figuring out how to use them and it is exceedingly difficult to find examples of similar code online.

iText7 provides the following classes that may be useful:

PdfPattern.Tiling
PatternColor
PdfPatternCanvas

It looks like you should be able to create a PdfPattern.Tiling object which references an image in some way and then create a PatternColor from that tiling object. Then you can set your canvas' fill color to the PatternColor you just created. An example of a function that does this is:

private void SetImageTilingFill(PdfCanvas canvas, PdfImageXObject img)
{      
    PdfPattern.Tiling tiling = new PdfPattern.Tiling((float)Inches2Points(img.GetHeight() / 96), (float)Inches2Points(img.GetWidth() / 96));  // create tiling object with width and height the size of the img
    tiling.GetResources().AddImage(img);// add the image as a resource?
    canvas.SetFillColor(new PatternColor(tiling)); // set fill color to PatternColor?
}

So far this approach has not been successful, my rectangle ends up solid black. Any suggestions would be much appreciated.

Using an image as a tile requires setting up the tile (it has a canvas to draw on). And then using it as a fill when drawing.

try (PdfWriter writer = new PdfWriter("tiling.pdf");
             PdfDocument document = new PdfDocument(writer)) {

            // creating image
            ImageData imageData = ImageDataFactory.create("wavy.png");
            PdfImageXObject imageXo = new PdfImageXObject(imageData);
            // setting up the tile
            PdfPattern.Tiling imageTile = new PdfPattern.Tiling(100, 100);
            new PdfPatternCanvas(imageTile, document)
                    .addXObjectFittedIntoRectangle(imageXo, new Rectangle(0, 0, 100, 100))
                    .release();


            PdfPage page = document.addNewPage();
            PdfCanvas canvas = new PdfCanvas(page);
            //using the tile
            canvas.setFillColor(new PatternColor(imageTile));
            canvas.rectangle(10, 10, 500, 900).fill();

            canvas.release();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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