Click here to Skip to main content
15,917,875 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
I want to add a logo/image dynamically code wise to an existing PDF file using asp.net with c#.
On trying below code logo is added but as a new pdf file. I want to add to the existing pdf file

What I have tried:

C#
private void AddLogo()
        {
            string pdfpath = Server.MapPath(".") + "/pdf/test.pdf";
            string imagepath = Server.MapPath(".") + "/logo/test.jpg";
            Document doc = new Document();

            try
            {
                PdfWriter.GetInstance(doc, new FileStream(pdfpath, FileMode.Create));
                doc.Open();

                //doc.Add(new Paragraph("GIF"));
                iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(imagepath);
                image.ScalePercent(24f);
                doc.Add(image);
            }
            catch (Exception ex)
            {
                //Log error;
            }
            finally
            {
                doc.Close();
            }
        }
Posted
Updated 1-Oct-16 7:19am
v3

Just a wild and crazy guess, but I think the reason why you are always creating new files is this line.

C#
PdfWriter.GetInstance(doc, new FileStream(pdfpath, FileMode.Create));


You are using FileMode.Create...you should probably change that to FileMode.OpenOrCreate or FileMode.Open.
 
Share this answer
 
Please try this
C#
using (Stream inputPdfStream = new FileStream(Server.MapPath("~") + "/pdf/test.pdf", FileMode.Open, FileAccess.Read, FileShare.Read))
           using (Stream inputImageStream = new FileStream(Server.MapPath("~") + "/logo/test.jpg", FileMode.Open, FileAccess.Read, FileShare.Read))
           using (Stream outputPdfStream = new FileStream(Server.MapPath("~") + "/pdf/Result.pdf", FileMode.Create, FileAccess.Write, FileShare.None))
           {
               var reader = new PdfReader(inputPdfStream);
               var stamper = new PdfStamper(reader, outputPdfStream);
               var pdfContentByte = stamper.GetOverContent(1);

               iTextSharp.text.Image image = iTextSharp.text.Image.GetInstance(inputImageStream);
               image.SetAbsolutePosition(100, 100);
               pdfContentByte.AddImage(image);
               stamper.Close();
           }
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900