CS.NET - Insert Text and Image in PDF Form Template



Insert Text and Image in PDF Form Template

// Reference ItextSharp

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        CreatePDFDocument( );
    }

    public void CreatePDFDocument( )
    {
        string pdfTemplate = @”D:\Main.pdf”;
 
        string imagePath = String.Empty;
 
        imagePath = @”D:\Sunset.jpg”;
 
        PdfReader pdfReader = null;
       
        FileStream pdfOutputFile = new FileStream(pdfTemplate, FileMode.Create);
 
        pdfReader = new PdfReader(@”D:Main.pdf”);
       
        PdfStamper pdfStamper = null;
 
        pdfStamper = new PdfStamper(pdfReader, pdfOutputFile);
 
        AcroFields testForm = pdfStamper.AcroFields;
 
        testForm.SetField(”textBox1″, “This is PDF  using iTextSharp ”);

        testForm.SetField(”textBox2″, “This is PDF using iTextSharp ”);
 
        iTextSharp.text.Image instanceImg = iTextSharp.text.Image.GetInstance(imagePath);
 
        PdfContentByte overContent = pdfStamper.GetOverContent(1);

        float[] imageArea = testForm.GetFieldPositions(”testImage1″);
 
        iTextSharp.text.Rectangle imageRect = new Rectangle(imageArea[1], imageArea[2], imageArea[3], imageArea[4]);
 
        instanceImg.ScaleToFit(imageRect.Width, imageRect.Height);
 
        instanceImg.SetAbsolutePosition(imageArea[3] - instanceImg.ScaledWidth + 
        (imageRect.Width - instanceImg.ScaledWidth)
        /   2, imageArea[2] + (imageRect.Height - instanceImg.ScaledHeight) / 2);
 
        overContent.AddImage(instanceImg);

        pdfStamper.FormFlattening = true;
 
        pdfStamper.Close();
 
        pdfReader.Close();

    }
}

Share |

 Cant find the page you are looking for?
 Help us to improve by adding the content that you are looking for.
 Leave a feedback
 We look forward to hear your comments and feedback.