Tile an image in PDF using iText7 - c#

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

Related

How to fill a shape with bitmap or mask a bitmap with shape in iText 7?

I want to fill a shape with a bitmap, in other words, mask a bitmap with a shape. I can't find a direct example. I am using iText 7 and C#.
You can fill a shape with a bitmap by making that shape a clip path and adding the bitmap, e.g. like this:
using (PdfWriter writer = new PdfWriter(...))
using (PdfDocument pdfDoc = new PdfDocument(writer))
{
ImageData data = ImageDataFactory.Create(...);
PdfCanvas pdfCanvas = new PdfCanvas(pdfDoc.AddNewPage());
pdfCanvas.SaveState()
.MoveTo(100, 100)
.LineTo(300, 200)
.LineTo(400, 400)
.LineTo(200, 300)
.ClosePath()
.EoClip()
.EndPath();
pdfCanvas.AddImageAt(data, 100, 100, false);
pdfCanvas.RestoreState();
}
(AddImageWithMask test testAddImageInShape)
The result looks like this:

Image is not drawn at the correct spot

Bitmap image = ReadBitmap("image.png");
Bitmap imageCopy = new Bitmap(image);
Bitmap canvas = new Bitmap(imageCopy.Width+100, imageCopy.Height);
// From this bitmap, the graphics can be obtained, because it has the right PixelFormat
using(Graphics g = Graphics.FromImage(canvas))
{
// Draw the original bitmap onto the graphics of the new bitmap
g.DrawImage(image, 0, 0);
}
// Use tempBitmap as you would have used originalBmp
InputPictureBox.Image = image;
OutputPictureBox.Image = canvas;
I haven't understood the output of this c# code.
The original image is not placed at the correct position. It should have been at (0, 0).
Also, I need a black background.
So, what is going on and how to correct this?
You are loading an Image, then a copy of this source is created using:
Bitmap bitmap = new Bitmap();
When you create a copy of an Image this way, you sacrifice/alter some details:
Dpi Resolution: if not otherwise specified, the resolution is set to the UI resolution. 96 Dpi, as a standard; it might be different with different screen resolutions and scaling. The System in use also affects this value (Windows 7 and Windows 10 will probably/possibly provide different values)
PixelFormat: If not directly copied from the Image source or explicitly specified, the PixelFormat is set to PixelFormat.Format32bppArgb.
From what you were saying, you probably wanted something like this:
var imageSource = Image.FromStream(new MemoryStream(File.ReadAllBytes(#"[SomeImageOfLena]"))), true, false)
var imageCopy = new Bitmap(imageSource.Width + 100, imageSource.Height, imageSource.PixelFormat))
imageCopy.SetResolution(imageSource.HorizontalResolution, imageSource.VerticalResolution);
using (var g = Graphics.FromImage(imageCopy)) {
g.Clear(Color.Black);
g.CompositingMode = CompositingMode.SourceCopy;
g.InterpolationMode = InterpolationMode.HighQualityBicubic;
g.DrawImage(imageSource, (imageCopy.Width - imageSource.Width) / 2, 0);
pictureBox1.Image?.Dispose();
pictureBox2.Image?.Dispose();
pictureBox1.Image = imageSource;
pictureBox2.Image = imageCopy;
}
This is the result:
(The upper/lower frame black color is actually the Picturebox background color)
When the original Image Dpi Resolution is different from the base Dpi Resolution used when creating an Image copy with new Bitmap(), your results may be different from what is expected.
This is what happens with a source Image of 150, 96 and 72 Dpi in the same scenario:
Another important detail is the IDisposable nature of the Image object.
When you create one, you have to Dispose() of it; explicitly, calling the Dispose method, or implicitly, enclosing the Image contructor in a Using statement.
Also, possibly, don't assign an Image object directly loaded from a FileStream.
GDI+ will lock the file, and you will not be able to copy, move or delete it.
With the file, all resources tied to the Images will also be locked.
Make a copy with new Bitmap() (if you don't care of the above mentioned details), or with Image.Clone(), which will preserve the Image Dpi Resolution and PixelFormat.
I am not completely clear on what you are actually needing to do. But anyway, here is a WPF-friendly example of how to draw an image at a specific position inside another image.
Note if all you want to do is display the image in different size and/or put a black border around it, there are much simpler ways to do simply that, without having to create a second image, such as just laying out the image inside a panel that already has the border style you want.
Notice that I am using classes from the System.Windows.Media namespace because that is what WPF uses. These don't mix easily with the older classes from System.Drawing namespace (some of the class names conflict, and Microsoft's .Net framework lacks built-in methods for converting objects between those types), so normally one needs to simply decide whether to use one or the other sets of drawing tools. I assume you have been trying to use System.Drawing. Each has its own pros and cons that would take too long to explain here.
// using System.Windows.Media;
// using System.Windows.Media.Imaging;
private void DrawTwoImages()
{
// For InputPictureBox
var file = new Uri("C:\\image.png");
var inputImage = new BitmapImage(file);
// If your image is stored in a Resource Dictionary, instead use:
// var inputImage = (BitmapImage) Resources["image.png"];
InputPicture.Source = inputImage;
// imageCopy isn't actually needed for this example.
// But since you had it in yours, here is how it's done, anyway.
var imageCopy = inputImage.Clone();
// Parameters for setting up our output picture
int leftMargin = 50;
int topMargin = 5;
int rightMargin = 50;
int bottomMargin = 5;
int width = inputImage.PixelWidth + leftMargin + rightMargin;
int height = inputImage.PixelHeight + topMargin + bottomMargin;
var backgroundColor = Brushes.Black;
var borderColor = (Pen) null;
// Use a DrawingVisual and DrawingContext for drawing
DrawingVisual dv = new DrawingVisual();
using (DrawingContext dc = dv.RenderOpen())
{
// Draw the black background
dc.DrawRectangle(backgroundColor, borderColor, new Rect(0, 0, width, height));
// Copy input image onto output image at desired position
dc.DrawImage(inputImage, new Rect(leftMargin, topMargin,
inputImage.PixelWidth, inputImage.PixelHeight));
}
// For displaying output image
var rtb = new RenderTargetBitmap( width, height, 96, 96, PixelFormats.Pbgra32 );
rtb.Render(dv);
OutputPicture.Source = rtb;
}

Barcode i25 using ItextSharp

i am using BarcodeInter25 class to make barcode. I am able to make it but its just blur how can it become more sharp ??
also its background white colour is not completely white
My Code:
BarcodeInter25 code25 = new BarcodeInter25();
Rectangle r = new iTextSharp.text.Rectangle(38, 152);
code25.ChecksumText = false;
code25.Code = "some digits";
code25.BarHeight = 2
System.Drawing.Image i = code25.CreateDrawingImage(System.Drawing.Color.Black, System.Drawing.Color.White);
MemoryStream ms = new MemoryStream();
i.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
Image img = Image.GetInstance(ms.ToArray());
ms.Dispose();
Looking at your code, it should be obvious why the barcode is blurry. You convert it to a System.Drawing.Image (making it a raster image) and then you convert it to an iTextSharp.text.Image (but by then the image is already blurry).
The correct way to achieve what you want, is to create an iTextSharp.text.Image straight from the barcode (do not pass through System.Drawing.Image). This can be done like this:
BarcodeInter25 code25 = new BarcodeInter25();
Rectangle r = new iTextSharp.text.Rectangle(38, 152);
code25.ChecksumText = false;
code25.Code = "some digits";
code25.BarHeight = 2;
PdfContentByte cb = writer.DirectContent;
Image img = code25.CreateImageWithBarcode(cb, null, null);
Now the Image object won't be a raster image (with pixels that make the lines blurry), but it will be a true vector image (no pixels, but instructions such as moveTo(), lineTo() and stroke()). Vector data has the advantage that it is resolution independent: you can zoom in and zoom out as much as you want, it will always be sharp.
This is explained in Chapter 10 of my book where you'll find the Barcodes example. In that chapter, you'll also discover the setFont() (or in iTextSharp the Font property). I quote from the API documentation:
public void setFont(BaseFont font)
Sets the text font.
Parameters:
font - the text font. Set to null to suppress any text
So if you don't want to see any text, you can add the following line to the above code snippet:
code25.Font = null;
You should avoid re-sizing by any means. The output is most likely pixel-perfect but when you scale it up/down a bilinear filter will smooth it rendering it blurry.
I had the same exact problem by embedding a QRC code in a PDF and solved it by avoiding a resize.
If you really need a different size apply it programmatically in code by using the correct interpolation algorithm.

How to overlap images and store them in new image objects

I have two images,now i want to overlay the images,such that the other image appears on center or left corner of the other image,and then when finally both the images are overlayed i can store it in another new image object,and i want to all this in code behind only not xaml,how to do this?
if (((Grid)sender).Children.Count > 0)
{
gridBackground = (ImageBrush)(((Grid)sender).Background);
gridBackImage = new System.Windows.Controls.Image();
gridBackImage.Source = gridBackground.ImageSource;
}
System.Windows.Controls.Image imgRejectIcon;
if (((Grid)sender).Children.Count > 0)
{
imgRejectIcon = (System.Windows.Controls.Image)(((Grid)sender).Children[0]);
}
Now i want to merge gridBackImage and imgRejection and store it in new image object
You can arrange your two Images in any way that you want and I'll leave that code for you to do (it'd much simpler to do in XAML). In WPF, all UI controls extend the Visual class. This is very useful for making BitmapImages from UI controls, when used with the RenderTargetBitmap.Render method.
First, arrange your two Image controls into a Grid, or other container control, and then you can pass the container control to the RenderTargetBitmap.Render method and create an Image something like this:
RenderTargetBitmap renderTargetBitmap =
new RenderTargetBitmap(width, height, 96, 96, PixelFormats.Pbgra32);
renderTargetBitmap.Render(yourContainerControl);
PngBitmapEncoder pngImage = new PngBitmapEncoder();
pngImage.Frames.Add(BitmapFrame.Create(renderTargetBitmap));
using (Stream fileStream = File.Create(filePath))
{
pngImage.Save(fileStream);
}

How to generate a image with text and images in C#

I have several paragraphs of text and couple of pictures between these paragraphs.
Now, I want to generate a picture using these materials, merging them vertically. But all the blocks of the text and pictures can not have bigger width than that of the generating picture, which means I have to zoom out the origin pictures, and fill each paragraph of text into a rectangle to fit the width.
Here is the tough thing:
To figure out the size of the rectangle to contain the text, I need use Graphics.MeasureString() method, which needs an instance of Graphics used to generate my picture(now, I'm using a blank template picture). But I do not know the exact size of this Graphics until I figure out all the sizes of rectangles and pictures.
Is there any method to get an instance of Graphics without source image?
Or is there any other method to do this work?
hope this could help dude .
http://chiragrdarji.wordpress.com/2008/05/09/generate-image-from-text-using-c-or-convert-text-in-to-image-using-c/
https://web.archive.org/web/20131231000000/http://tech.pro/tutorial/654/csharp-snippet-tutorial-how-to-draw-text-on-an-image
http://www.codeproject.com/Questions/388845/HOW-TO-MAKE-HIGH-QAULITY-IMAGE-WITH-TEXT-IN-Csharp
thank you
For people how are intrested in a WPF solution (as asked):
public static BitmapSource CreateImage(string text, double width, double heigth)
{
// create WPF control
var size = new Size(width, heigth);
var stackPanel = new StackPanel();
var header = new TextBlock();
header.Text = "Header";
header.FontWeight = FontWeights.Bold;
var content = new TextBlock();
content.TextWrapping = TextWrapping.Wrap;
content.Text = text;
stackPanel.Children.Add(header);
stackPanel.Children.Add(content);
// process layouting
stackPanel.Measure(size);
stackPanel.Arrange(new Rect(size));
// Render control to an image
RenderTargetBitmap rtb = new RenderTargetBitmap((int)stackPanel.ActualWidth, (int)stackPanel.ActualHeight, 96, 96, PixelFormats.Pbgra32);
rtb.Render(stackPanel);
return rtb;
}

Categories