Garima Bansal

Garima Bansal

  • 861
  • 681
  • 39.8k

itextsharp"Object reference not set to an instance of an object" error

May 30 2024 6:34 AM

I have the following code. I am getting error trying many solutions but none of them works

if (model.Pdfdoc != null)
{
    image = new byte[model.Pdfdoc.ContentLength];
    model.Pdfdoc.InputStream.Read(image, 0, image.Length);
    System.UInt32 mimetype;
    FindMimeFromData(0, null, image, 256, null, 0, out mimetype, 0);
    System.IntPtr mimeTypePtr = new IntPtr(mimetype);
    model.filetype = Marshal.PtrToStringUni(mimeTypePtr);
    Marshal.FreeCoTaskMem(mimeTypePtr);

    //WATER MARK IMAGE 
    iTextSharp.text.Image img = iTextSharp.text.Image.GetInstance(Server.MapPath("~/Images/Watermark.png"));
    img.SetAbsolutePosition(0, 80f);
    img.ScaleAbsolute(600f, 600f);
    
    PdfReader readerInvoice = new PdfReader(image);
    int n = readerInvoice.NumberOfPages;

    MemoryStream msPIA = new MemoryStream();

    using (MemoryStream ms1 = new MemoryStream())
    {
        // Create the stamper
        //using (PdfStamper stamper = new PdfStamper(readerInvoice, ms1))
        using (PdfStamper stamper = new PdfStamper(readerInvoice, ms1, '\0', true)) error in this line
        {
            for (int page = 1; page <= n; page++)
            {
                PdfContentByte over = stamper.GetOverContent(page);
                over.AddImage(img);


            }
            stamper.Close();
        }
        msPIA = ms1;

    }
    byte[] bytesInStream = msPIA.ToArray(); // simpler way of converting to array
    msPIA.Close();

    image = bytesInStream;

    if (model.filetype.Equals("application/pdf"))
    {
        model.Pdf = image;
    }
}

 


Answers (7)