Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PDFSharp Insert an image in a pdf using a PdfTextField as the position and size reference

We want to insert a png image with a (drawn)signature into a PDF with PDFSharp. The position and size of the image is determined by a invisible PdfTextField that we created previously in the PDF. With our current code the problem is: How can we get the page reference from our PdfTextField (the page that contains this field)?

Code:

PdfDocument document = PdfReader.Open("C:\\filex.pdf", PdfDocumentOpenMode.Modify);

// Get the root object of all interactive form fields
PdfAcroForm form = document.AcroForm;

// Get all form fields of the whole document
PdfAcroField.PdfAcroFieldCollection fields = form.Fields;

//Get the invisible PdfTextField used as position and size reference
PdfTextField signatureposition= (PdfTextField)fields["thesignature"];

PdfArray signaturerect= (PdfArray)signatureposition.Elements["/Rect"];
string x = signaturerect.Elements[0].ToString();
string y = signaturerect.Elements[1].ToString();
string w = signaturerect.Elements[2].ToString();
string h = signaturerect.Elements[3].ToString();

string imagepath= "C:\\signature.png";

//how to get the correct page reference respect the especified field?
PdfPage page= signatureposition.Owner.Pages[???];

XGraphics gfx = XGraphics.FromPdfPage(page);
XImage image = XImage.FromFile(imagepath);
gfx.DrawImage(image, x, y, width, height);
like image 318
VSP Avatar asked Dec 30 '25 22:12

VSP


1 Answers

In the end we solved it creating this function:

   protected int PaginaCampo(string campofirma, PdfDocument document)
{
    for (int i = 0; i < document.Pages.Count; i++)
    {
        PdfAnnotations anotations = document.Pages[i].Annotations;
        for (int j = 0; j < anotations.Count; j++)
        {
            if (anotations[j].Title != campofirma) continue;
            return i;
        }
    }
    return -1;
}

Not the best solution but it works...if someone adds a better one we will give the correct answer to him/her

like image 97
VSP Avatar answered Jan 01 '26 12:01

VSP