user1304444
user1304444

Reputation: 1753

.net mvc3 iTextSharp how to add image to pdf in memory stream and return to browser

I have a .pdf file stored in my database, and I have a signature file (.png) stored in my database. I am trying to use iTextSharp to add the signature image to the .pdf file, and display the result to the browser.

Here is my code:

        byte[] file = Repo.GetDocumentBytes(applicantApplication.ApplicationID, documentID);
        byte[] signatureBytes = Repo.GetSignatureBytes((Guid)applicantApplicationID, signatureID);

        iTextSharp.text.Image signatureImage = iTextSharp.text.Image.GetInstance(signatureBytes);                      
        iTextSharp.text.Document document = new iTextSharp.text.Document(); 

        using (System.IO.MemoryStream ms = new System.IO.MemoryStream(file, 0, file.Length, true, true))
        {
            PdfWriter writer = PdfWriter.GetInstance(document, ms);
            document.Open();

            signatureImage.SetAbsolutePosition(200, 200);
            signatureImage.ScaleAbsolute(200, 50);
            document.Add(signatureImage);

            document.Close();

            return File(ms.GetBuffer(), "application/pdf");
        }

The page loads, and there is a .pdf with a signature, but the original document is nowhere to be found. It looks like I'm creating a new .pdf file and putting the image in there instead of editing the old .pdf file.

I have verified that the original .pdf document is being loaded into the "file" variable. I have also verified that the length of the MemoryStream "ms" is the same as the length of the byte[] "file".

Upvotes: 0

Views: 5777

Answers (1)

user1304444
user1304444

Reputation: 1753

I ended up doing something like this in my repository:

        using (Stream inputPdfStream = new MemoryStream(file, 0, file.Length, true, true))
        using (Stream inputImageStream = new MemoryStream(signatureBytes, 0, signatureBytes.Length, true, true))
        using (MemoryStream outputPdfStream = new MemoryStream())
        {
            var reader = new PdfReader(inputPdfStream);
            var stamper = new PdfStamper(reader, outputPdfStream);
            var cb = stamper.GetOverContent(1);

            iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
            image.SetAbsolutePosition(400, 100);
            image.ScaleAbsolute(200, 50);
            cb.AddImage(image);

            stamper.Close();

            return outputPdfStream.GetBuffer();
       }

I adapted it from a few other answers on StackOverflow

Upvotes: 1

Related Questions