简体   繁体   中英

Why doesn't an Image show up when I add it to a Document using iTextSharp?

Contextt: I am opening an existing, interactive PDF form containing AcroForm fields. I tried to add an image to a rectangle field in the PDF form like this:

string path = HttpContext.Current.Server.MapPath("includes");
string newFile = HttpContext.Current.Server.MapPath("Tmp") + "/completed_gray" +".pdf";
string imagepath = HttpContext.Current.Server.MapPath("Tmp");
Document doc = new Document();
try {
    PdfWriter.GetInstance(doc, new FileStream(newFile, FileMode.Open));
    doc.Open();
    iTextSharp.text.Image gif = iTextSharp.text.Image.GetInstance(imagepath + "/CUstomRep_Eng_Col_1_V1.png");
    iTextSharp.text.Rectangle rect = pdfStamper.AcroFields.GetFieldPositions("img_1_space")[0].position;
    gif.ScaleAbsolute(rect.Width, rect.Height);
    gif.SetAbsolutePosition(rect.Left, rect.Bottom);  
    doc.Add(gif);
}
catch (Exception ex) {
    //Log error;
}
finally {
    doc.Close();
}

The image doesn't show up in the resulting PDF.

You're creating a document using the "5 steps to create a PDF document" as documented in my books.

  1. create a Document object.
  2. create a PdfWriter instance.
  3. open the document.
  4. add content to the document.
  5. close the document.

This contradicts with what you actually want to do: I want to add an Image in a placeholder defined by an AcroForm field.

Why are you saying you want one thing, and doing something else? Beats me. Probably because you didn't want to read the documentation.

You need something like this:

  1. Create a PdfReader instance.
  2. Create a PdfStamper instance.
  3. Ask the stamper for information about the fields.
  4. Add content to a page using the stamper instance.
  5. Close the stamper.

In answer to your question: why doesn't my image show up in my document?

Support the coordinates of the field in the existing document are lower-left corner x = 600, y = 600 and upper-right corner x = 700, y = 700, then you are adding the image outside the visible area of the page you're creating. When you use new Document(); , you're creating a document where the lower-left corner is x = 0, y = 0 and the upper-right corner is x = 595, y = 842.

In that case, you're adding the image to the document, but it's not visible because you've added it outside the rectangle that defines the page.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM