leryler
leryler

Reputation: 1

iText insert image in pdf at specific element or at the end of text

I'm asking because I can't find proper documentation for iText, only API reference.

Is there a way to add an image in a PDF with iText after retrieving some element or text position using only iText?

I found a way to find end of text on a page using regex location strategy but is there a way to just search elements instead of listing every PdfTextLocation with ".*" regex.

var regex = new Regex(".*");
var strat = new RegexBasedLocationExtractionStrategy(regex);

PdfCanvasProcessor pdfCanvasProcessor = new PdfCanvasProcessor(strat);
pdfCanvasProcessor.ProcessPageContent(page);

var locs = strat.GetResultantLocations();

var rect = locs.OrderBy(r => r.GetRectangle().GetY()).FirstOrDefault();
var x = rect?.GetRectangle().GetX() ?? 0;
var y = rect?.GetRectangle().GetY() ?? 0;

Upvotes: 0

Views: 63

Answers (2)

Glenner003
Glenner003

Reputation: 1597

A pdf document has no notion of content structure, the order in which items are drawn is unrelated to where they will appear on the page.

So the only way to know where there is content and where not is to process all content.

In your case, the regex is only ballast, but iText doesn't contain an alternative out of the box. But you can easily build one yourself starting from the RegexBasedLocationExtractionStrategy code.

Upvotes: 1

shariff mikangi
shariff mikangi

Reputation: 1

I think in this case you are missing something, where are you placing your image? A canvas or? But perhaps this can guide you as per your codes and logics

PdfCanvas document = new PdfCanvas(page);
//string numericID = Convert.ToString(numericID1).Substring(0, 5); //ignore this encoding a GUID to my image

string name = ddl_Emp.Items[i].Text;
string qrData = $"{name}_{numericID}";
var objResult = objWrite.Write(qrData);
string fileName = $"{qrData}.bmp";
string Path1 = Server.MapPath($"~/EmpMaster/empqrcode/{fileName}");
var bmpbitmap = new Bitmap(objResult);

MemoryStream ms = new MemoryStream();

bmpbitmap.Save(ms, ImageFormat.Bmp);

iTextSharp.text.Image pdfImage = iTextSharp.text.Image.GetInstance(ms.ToArray());

pdfImage.ScaleToFit(20f, 20f);
pdfImage.Alignment = iTextSharp.text.Image.ALIGN_CENTER;

document.Add(pdfImage, x, y, 100, false);// you can choose the best offset for your condition
               
byte[] data = ms.ToArray();
FileStream fs = new FileStream(Path1, FileMode.Create);

fs.Flush(true);
fs.Write(data, 0, data.Length); 
 ms.Dispose();
 fs.Dispose();
 bmpbitmap.Dispose();
document.Close();

Upvotes: -1

Related Questions