1

I need to insert an image into an existing pdf at a specific location. I tried the answer at this question. But whatever different ways I do the image is being inserted at (0,0) position (bottom left corner). I tried another approach where instead of using stream I used Document class in iTextSharp as shown here. Now I am able to place the image at the desired position but this method is creating a new document with just this image. Most of the articles I searched are using PdfReader and PdfStamper so I think this is the recommended way. Any help is appreciated. Posting below code for both the methods I tried.

PdfStamper method

   private void AddImage(string filePath)
    {
        string imageURL = @"ImagePath\Image.jpg";

        using (Stream inputPdfStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        using (Stream inputImageStream = new FileStream(imageURL, FileMode.Open, FileAccess.Read))
        using (Stream outputPdfStream = new FileStream(@"ResultingPdfPath\Abcd.pdf", FileMode.Create, FileAccess.ReadWrite))
        {
            Image image = Image.GetInstance(inputImageStream);
            image.ScaleToFit(100, 100);

            var reader = new PdfReader(inputPdfStream);
            var stamper = new PdfStamper(reader, outputPdfStream);

            PdfContentByte content = stamper.GetUnderContent(1);
            image.SetAbsolutePosition(100f, 150f);
            content.AddImage(image);

            stamper.Close();

            reader.Close();
        }
    }

Document class method

    private void TestMessage(string filePath)
    {
        string imageURL = @"ImagePath\Image.jpg";

        Document doc = new Document(PageSize.A4);

        PdfWriter writer = PdfWriter.GetInstance(doc, new FileStream(filePath, FileMode.Open));

        doc.Open();

        iTextSharp.text.Image jpg = iTextSharp.text.Image.GetInstance(imageURL);
        jpg.ScaleToFit(140f, 120f);
        jpg.SetAbsolutePosition(100, 100);
        jpg.SpacingBefore = 10f;
        jpg.SpacingAfter = 1f;
        jpg.Alignment = Element.ALIGN_LEFT;
        doc.Add(jpg);
        doc.Close();
    }

Let me know if you need further information.

Community
  • 1
  • 1
Raj123
  • 971
  • 2
  • 12
  • 24
  • The code snippet "Document class method" is wrong: it creates a new document. The code snippet "PdfStamper method" is correct. You add the image twice at different positions, once under, once on top of the existing content. You are using hard-coded coordinates, not taking into account the page size (and the crop box) of the original PDF. Nevertheless, I don't believe your claim that the images are both added at the coordinate `(0, 0)`. Since you aren't telling the truth, your question can't be answered. PS: the line `stamper.FormFlattening = true;` is irrelevant and should be removed. – Bruno Lowagie Nov 30 '15 at 10:52
  • @BrunoLowagie I made some changes when trying different approaches and forgot to edit that before pasting it. I edited the question. Even when I try the edited code I couldn't get the desired results. Even if I am not taking into account the page size shouldn't the image position be changing based on the values I am giving in SetAbsolutePosition? And I don't understand that about not believing my claim? – Raj123 Nov 30 '15 at 11:12
  • You aren't telling us what you expect. What is the desired result? Are you expecting that the image gets *inserted* in a way that the other content *moves*? In that case, please give up: PDF doesn't allow you to do that. Are you not seeing the image? Maybe it's covered by an opaque shape or maybe it's added *outside* the visible area of the page. What I don't believe is that no matter what you add instead of `100f, 150f` in the line `image.SetAbsolutePosition(100f, 150f);` the image is always added at `0, 0`. That is not possible, hence I don't believe what you're saying. – Bruno Lowagie Nov 30 '15 at 11:24
  • @BrunoLowagie I want the image to be added at the position which I specify in SetAbsolutePosition. I even tried getting the size of the document and writing the code image.SetAbsolutePosition(width - 100f, height - 150f) but to no use. I can see the image but whatever I do, its always at the bottom left corner. And I don't want the image to move the content around. I thought my code to GetUnderContent makes the content overlap on the image (if required) or vice versa. And why are you so adamant that I am trying to hide something regarding my query? What would I gain by doing so? – Raj123 Nov 30 '15 at 12:35
  • When people say "it doesn't work" **without providing proof** (e.g. in the form of a PDF that can be inspected) and **without providing a** [SSCCE](http://sscce.org), I assume *that they don't want an answer.* Is there any other explanation? What else could I assume? I can't reproduce your problem. Thousands of developers succeeded in adding an image to an existing PDF by defining absolute coordinates, but you claim that "it doesn't work." How do you want me to respond? You give me the feeling that you don't really want help. If you did, you'd provide more info. – Bruno Lowagie Nov 30 '15 at 12:44
  • The answer is available in the following link [https://stackoverflow.com/a/45486484/6597375](https://stackoverflow.com/a/45486484/6597375) – Deepu Reghunath Aug 03 '17 at 14:24

1 Answers1

1

I adapted your method to accept variable out paths and positions and tested it with iTextSharp 5.5.7 like this:

[TestFixture]
class TestInsertImage
{
    /// iText stamp image on top not always working
    /// http://stackoverflow.com/questions/33898280/itext-stamp-image-on-top-not-always-working
    /// 
    [Test]
    public void AddStampToTestPdf()
    {
        Directory.CreateDirectory(@"C:\Temp\test-results\content\");

        AddImage(@"d:\Issues\stackoverflow\iText stamp image on top not always working\Multipage.pdf", @"C:\Temp\test-results\content\Multipage-stamp-Image-100-150.pdf", 100f, 150f);
        AddImage(@"d:\Issues\stackoverflow\iText stamp image on top not always working\Multipage.pdf", @"C:\Temp\test-results\content\Multipage-stamp-Image-150-100.pdf", 150f, 100f);
    }

    private void AddImage(string filePath, string outPath, float x, float y)
    {
        string imageURL = @"c:\Repo\GitHub\testarea\itext5\src\test\resources\mkl\testarea\itext5\layer\Willi-1.jpg";

        using (Stream inputPdfStream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
        using (Stream inputImageStream = new FileStream(imageURL, FileMode.Open, FileAccess.Read))
        using (Stream outputPdfStream = new FileStream(outPath, FileMode.Create, FileAccess.ReadWrite))
        {
            Image image = Image.GetInstance(inputImageStream);
            image.ScaleToFit(100, 100);

            var reader = new PdfReader(inputPdfStream);
            var stamper = new PdfStamper(reader, outputPdfStream);

            PdfContentByte content = stamper.GetUnderContent(1);
            image.SetAbsolutePosition(x, y);
            content.AddImage(image);

            stamper.Close();

            reader.Close();
        }
    }
}

The results are included below.

As you see, the positioning information clearly are respected, and the image is definitely not always at the bottom left corner.

If this indeed does not work for the OP, he is keeping information from us required to help him.

Multipage-stamp-Image-100-150.pdf

At 100, 150

Created using

AddImage(@"d:\Issues\stackoverflow\iText stamp image on top not always working\Multipage.pdf", @"C:\Temp\test-results\content\Multipage-stamp-Image-100-150.pdf", 100f, 150f);

Multipage-stamp-Image-150-100.pdf

At 150, 100 Created using:

AddImage(@"d:\Issues\stackoverflow\iText stamp image on top not always working\Multipage.pdf", @"C:\Temp\test-results\content\Multipage-stamp-Image-150-100.pdf", 150f, 100f);
mkl
  • 90,588
  • 15
  • 125
  • 265
  • If anyone wonders like Damir Makhmudov in his meanwhile deleted answer how to *specify number of page to insert image*: The `1` in `stamper.GetUnderContent(1)` selects the UnderContent of page 1. – mkl Jul 17 '17 at 17:33