Placeholder to insert image on PDF

I am creating PDF’s for expense reports and I would like to allow my end user to attach images to the PDF. Is this possible?

Hi,

If you want to add images to a PDF page, see the following example:

If you want to add images as embedded files (attachments), see the following example:

I hope this helps.

Regards,
Mario

Mario,

What I am looking for is a way to allow the person who is sent the PDF the opportunity to attach an image. The recipient does not have access to the program generating the PDF.

Basically a “click here to add an image” within the PDF.

Hi,

Apologies for the late response!

After investigating Adobe Acrobat’s behavior, we concluded that this scenario is possible by using image fields, which are, in fact, button fields with specific customizations.

Here is a code snippet that shows how to create a PDF file with an image field using GemBox.Pdf:

var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

using (var document = new PdfDocument())
{
    var page = document.Pages.Add();

    var imageButton = document.Form.Fields.AddButton(page, 100, 500, 72, 80);

    // This is required so that the 'Select Image' dialog window is shown when clicking the button.
    imageButton.Actions.AddRunJavaScript("event.target.buttonImportIcon();");
    var imageButtonAppearance = imageButton.Appearance;

    // Field name must end with '_af_image' and and LabelPlacement must be set to IconOnly
    // so that Adobe Reader shows the 'image placeholder' icon on the button.
    imageButton.Name += "_af_image";
    imageButtonAppearance.LabelPlacement = PdfTextPlacement.IconOnly;

    // These are optional, but Adobe Acrobat sets these values when creating an image button.
    imageButtonAppearance.BorderColor = PdfColor.FromGray(0.75293);
    imageButtonAppearance.BackgroundColor = PdfColors.White;

    document.Save(Path.Combine(desktop, "ImageButton.pdf"));
}

After your end user inserts images into image buttons, you can extract those images using the following code snippet:

var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

using (var document = PdfDocument.Load(Path.Combine(desktop, "ImageButton.pdf")))
{
    foreach (PdfButtonField imageButton in document.Form.Fields.Where(f => f.FieldType == PdfFieldType.Button && f.Name.EndsWith("_af_image")))
        if (imageButton.Appearance.Icon is PdfForm iconForm &&
            iconForm.Content.Elements.All(flattenForms: false).SingleOrDefault(e => e.ElementType == PdfContentElementType.Image) is PdfImageContent imageContent)
        {
            var extension = imageContent.Image.GetDictionary().Stream.Filters.Any(f => f.FilterType == PdfFilterType.DCTDecode) && imageContent.Image.SoftMask is null ? ".jpg" : ".png";
            imageContent.Save(Path.Combine(desktop, imageButton.Name.Substring(0, imageButton.Name.Length - "_af_image".Length) + extension));
        }
}

Regards,
Stipo