Tech Off Post

Single Post Permalink

View Thread: ASP.NET and iTextSharp (free PDF Generator for .NET)
  • User profile image
    robnisbet

    Thanks <itsnotabug> I read up a bit on watermarks etc and using the "UnderConent". My code now looks like this for anyone interested. I read the original PDF in, scale the image, find the last page and add the image, then save the pdf again to a different filename. Brilliant!

    Thanks!

                PdfReader reader = new PdfReader(myoriginalPDFFileName);
               
                PdfStamper stamper = new PdfStamper(reader, new FileStream(
                    mynewPDFFileName, FileMode.Create));
                           
                Single x=0;
                Single y=0;
                iTextSharp.text.Rectangle rect = reader.GetPageSizeWithRotation(1);
                iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(myImageName);
                if (img.Width > rect.Width || img.Height > rect.Height)
                {
                    img.ScaleToFit(rect.Width, rect.Height);
                    x = (rect.Width - img.ScaledWidth) / 2;               
                    //y = (rect.Height - img.ScaledHeight) / 2;
                    y = 0; //Set at bottom
                }
                else
                {
                    x = (rect.Width - img.Width) / 2;
                    y = (rect.Height - img.Height) / 2;
                }
                img.SetAbsolutePosition(x, y);

                int pageCount = reader.NumberOfPages;
                PdfContentByte underContent = stamper.GetUnderContent(pageCount);

                underContent.AddImage(img);

                // flatten form fields and close document
                stamper.FormFlattening = true;
                stamper.Close();