插入图片
1 using System.IO; 2 using iTextSharp.text; 3 using iTextSharp.text.pdf; 4 5 class Program 6 { 7 static void Main(string[] args) 8 { 9 using (Stream inputPdfStream = new FileStream("input.pdf", FileMode.Open, FileAccess.Read, FileShare.Read)) 10 using (Stream inputImageStream = new FileStream("some_image.jpg", FileMode.Open, FileAccess.Read, FileShare.Read)) 11 using (Stream outputPdfStream = new FileStream("result.pdf", FileMode.Create, FileAccess.Write, FileShare.None)) 12 { 13 var reader = new PdfReader(inputPdfStream); 14 var stamper = new PdfStamper(reader, outputPdfStream); 15 var pdfContentByte = stamper.GetOverContent(1); 16 17 Image image = Image.GetInstance(inputImageStream); 18 image.SetAbsolutePosition(100, 100); 19 pdfContentByte.AddImage(image); 20 stamper.Close(); 21 } 22 } 23 }
iTextSharp.text.Image
SetAbsolutePosition()有2个参数,第一个参数是X轴坐标,第二个参数是Y轴坐标,使用PDF坐标系,文档的左下角为坐标原点。
ScalePercent() 缩放比,
获取表单位置
1 IList<AcroFields.FieldPosition> fieldPositions = fields.GetFieldPositions("fieldNameInThePDF"); 2 if (fieldPositions == null || fieldPositions.Count <= 0) throw new ApplicationException("Error locating field"); 3 AcroFields.FieldPosition fieldPosition = fieldPositions[0]; 4 left = fieldPosition.position.Left; 5 right = fieldPosition.position.Right; 6 top = fieldPosition.position.Top; 7 bottom = fieldPosition.position.Bottom; 8 if (rotation == 90) 9 { 10 left = fieldPosition.position.Bottom; 11 right = fieldPosition.position.Top; 12 top = pageSize.Right - fieldPosition.position.Left; 13 bottom = pageSize.Right - fieldPosition.position.Right; 14 }
获取文字位置
1 public class RectAndText { 2 public iTextSharp.text.Rectangle Rect; 3 public String Text; 4 public RectAndText(iTextSharp.text.Rectangle rect, String text) { 5 this.Rect = rect; 6 this.Text = text; 7 } 8 }
1 public class MyLocationTextExtractionStrategy : LocationTextExtractionStrategy { 2 //Hold each coordinate 3 public List<RectAndText> myPoints = new List<RectAndText>(); 4 5 //Automatically called for each chunk of text in the PDF 6 public override void RenderText(TextRenderInfo renderInfo) { 7 base.RenderText(renderInfo); 8 9 //Get the bounding box for the chunk of text 10 var bottomLeft = renderInfo.GetDescentLine().GetStartPoint(); 11 var topRight = renderInfo.GetAscentLine().GetEndPoint(); 12 13 //Create a rectangle from it 14 var rect = new iTextSharp.text.Rectangle( 15 bottomLeft[Vector.I1], 16 bottomLeft[Vector.I2], 17 topRight[Vector.I1], 18 topRight[Vector.I2] 19 ); 20 21 //Add this to our main collection 22 this.myPoints.Add(new RectAndText(rect, renderInfo.GetText())); 23 } 24 }
文字位置使用代码
//Create an instance of our strategy var t = new MyLocationTextExtractionStrategy(); //Parse page 1 of the document above using (var r = new PdfReader(testFile)) { var ex = PdfTextExtractor.GetTextFromPage(r, 1, t); } //Loop through each chunk found foreach (var p in t.myPoints) { Console.WriteLine(string.Format("Found text {0} at {1}x{2}", p.Text, p.Rect.Left, p.Rect.Bottom)); }