public static List <PDFCompare.Comparer.TextItem> SearchPdfFile(string fileName, String searchText, int page = -1) { if (!File.Exists(fileName)) { throw new FileNotFoundException(FILE_NOT_FOUND, fileName); } var findedItems = new List <PDFCompare.Comparer.TextItem>(); using (PdfReader pdfReader = new PdfReader(fileName)) { var strategy = new PDFCompare.Comparer.LocationExtractionStrategy(); bool oneTime = page > 0; if (page == -1) { page = 1; } for (; page <= pdfReader.NumberOfPages; page++) { strategy.Page = page; PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy); List <PDFCompare.Comparer.TextItem> items = strategy.GetTextItems(); foreach (var item in items) { var word = item.Text; if (word == searchText) { findedItems.Add(item); } } if (oneTime) { break; } } } return(findedItems); }
static public bool PlaceImageOnLabel(string input, string output, string label, string imgFile, string widthParam, string heightParam, bool center) { if (!File.Exists(input)) { throw new FileNotFoundException(FILE_NOT_FOUND, input); } if (!File.Exists(imgFile)) { throw new FileNotFoundException(FILE_IMAGE_NOT_FOUND, imgFile); } bool labelFinded = false; // Проверим параметры // widthParam, heightParam должны принимать значение "", null, fit, или число. bool scaleByWidth = false; bool scaleByHeight = false; float width = 0; float height = 0; int result; if (string.IsNullOrEmpty(widthParam)) { ; } // пропускаем else if (Int32.TryParse(widthParam, out result)) { width = result; scaleByWidth = true; } else if (widthParam == "fit") { scaleByWidth = true; } else { throw new ArgumentException(); } if (string.IsNullOrEmpty(heightParam)) { ; } // пропускаем else if (Int32.TryParse(heightParam, out result)) { height = result; scaleByHeight = true; } else if (heightParam == "fit") { scaleByHeight = true; } else { throw new ArgumentException(); } System.IO.FileStream fs = new FileStream(output, FileMode.Create); using (PdfReader pdfReader = new PdfReader(input)) { PdfStamper stamper = new PdfStamper(pdfReader, fs); iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(imgFile); img.SetAbsolutePosition(0, 0); for (int page = 1; page <= pdfReader.NumberOfPages; page++) { var strategy = new PDFCompare.Comparer.LocationExtractionStrategy(); strategy.Page = page; PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy); List <PDFCompare.Comparer.TextItem> items = strategy.GetTextItems(); PdfContentByte over = stamper.GetOverContent(page); foreach (var item in items) { var word = item.Text; if (word == label) { float rotateDegrees = 0; Vector leftBottom = item.DescentLine.GetStartPoint(); Vector rightTop = item.AscentLine.GetEndPoint(); float offsetX = leftBottom[0]; float offsetY = leftBottom[1]; // GetPageSize - возвращает размер без учета ориентации(альбомная, вертикальная), т.е. в случае альбомной width и height // будут перепутаны при отображении на экране и позиционировании, поэтому нужно делать GetPageSizeWithRotation. iTextSharp.text.Rectangle pagesize = pdfReader.GetPageSizeWithRotation(page); PdfTemplate template = over.CreateTemplate(img.Width, img.Height); template.AddImage(img); var matrix = new System.Drawing.Drawing2D.Matrix(); // Трансформации применяются в обратном порядке // Vector v = item.DescentLine.GetEndPoint().Subtract(item.DescentLine.GetStartPoint()); rotateDegrees = (float)(Math.Atan2((double)v[1], (double)v[0]) * 180 / Math.PI); int pageRotation = pdfReader.GetPageRotation(page); // Если страница повернута, то мы получаем координаты на неповернутой странице, // а AddTemplate делает в координатах повернутой. // Поэтому преобразуем штамп обратно в координаты неповернутой. switch (pageRotation) { case 90: matrix.Translate(0, pagesize.Height); break; case 180: matrix.Translate(pagesize.Width, pagesize.Height); break; case 270: matrix.Translate(pagesize.Width, 0); break; } if (pageRotation != 0) { matrix.Rotate(360 - pageRotation); } // Сдвинем штрих код на свое место matrix.Translate(offsetX, offsetY); // Повернем штрихкод как текст повернут float w = (item.DescentLine.GetEndPoint().Subtract(item.DescentLine.GetStartPoint())).Length; // img.ScaleToFit(w, w*img.Height/img.Width); matrix.Rotate(rotateDegrees); // Отмасштабируем штрихкод чтобы вписать в п/у текста float widthLabel = width != 0 ? width : (item.DescentLine.GetEndPoint().Subtract(item.DescentLine.GetStartPoint())).Length; float heightLabel = height != 0 ? height : (item.AscentLine.GetStartPoint().Subtract(item.DescentLine.GetStartPoint())).Length; float scaleX = scaleByWidth ? widthLabel / img.Width : 0; float scaleY = scaleByHeight ? heightLabel / img.Height : 0; if (scaleX != 0 && scaleY == 0) { scaleY = scaleX; } if (scaleY != 0 && scaleX == 0) { scaleX = scaleY; } if (scaleX != 0 && scaleY != 0) { matrix.Scale(scaleX, scaleY); } // Применим шаблон и преобразования float[] elements = matrix.Elements; over.AddTemplate(template, elements[0], elements[1], elements[2], elements[3], elements[4], elements[5]); labelFinded = true; } } } stamper.Close(); } return(labelFinded); }