Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.0k views
in Technique[技术] by (71.8m points)

c# - itextsharp adding image to existing pdf

i am trying to add an image using itextsharp but not having any luck there are a ton of tutorials for adding an image to a new pdf doc but not and existing pdf so the .add menthod is not avaivlable

i am tring to do use the stamper write method to add image and i dont get any errors but no image shows up

PdfReader reader = new PdfReader(pdfIn); //get pdf

        if (File.Exists(pdfOut)) File.Delete(pdfOut); //reset 
        FileStream fs = new FileStream(pdfOut, FileMode.Create);

        PdfStamper stamper = new PdfStamper(reader, fs);
        try
        {
            //  Convert base64string to bytes array
            Byte[] bytes = Convert.FromBase64String(base64decode);
            iTextSharp.text.Image sigimage = iTextSharp.text.Image.GetInstance(bytes);//
            sigimage.SetAbsolutePosition(10, 10);
            sigimage.ScaleToFit(140f, 120f);
            stamper.Writer.Add(sigimage);
        }catch (DocumentException dex){//log exception here
        }catch (IOException ioex){//log exception here
        }



        AcroFields fields = stamper.AcroFields;
        //repeat for each pdf form fill field       
        fields.SetField("agencyName", name.Value);


        stamper.FormFlattening = true; // set to true to lock pdf from being editable
        stamper.Writer.CloseStream = true;
        stamper.Close();
        reader.Close();
        fs.Close();
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I think you try the following adding it to bytes

        PdfReader reader = new PdfReader(pdfIn)
        FileStream fs = new FileStream(pdfOut, FileMode.Create);
        var stamper = new PdfStamper(reader, fs);
        var pdfContentByte = stamper.GetOverContent(1);
        iTextSharp.text.Image sigimage = iTextSharp.text.Image.GetInstance(bytes);
        sigimage.SetAbsolutePosition(100, 100);
        pdfContentByte.AddImage(sigimage);

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...