PDFsharp icon indicating copy to clipboard operation
PDFsharp copied to clipboard

unable to check if a PdfDocument has an AcroForm inside

Open fedebona opened this issue 1 year ago • 2 comments

Reporting an Issue Here

If I open a PdfDocument PdfDocument inputPDFDocument = PdfReader.Open(pdfFile, PdfDocumentOpenMode.Import);

I'm not able to check if it has an AcroForm inside.

Expected Behavior

I should be able to check something like inputPDFDocument.AcroForm != null

Actual Behavior

inputPDFDocument.AcroForm raises an invalidoperation exception

Steps to Reproduce the Behavior

bool hasForm = (inputPDFDocument.AcroForm != null && inputPDFDocument.AcroForm.Elements.Count > 0); //unwanted Exception raised

fedebona avatar May 06 '24 15:05 fedebona

Hi, I’m also experiencing this issue and wanted to check if there have been any updates or progress on a potential fix. If there’s any additional information I can provide to help troubleshoot, please let me know. Thank you!

cbra-nbb avatar May 22 '25 06:05 cbra-nbb

Ran into this issue as well. Created an extension method that access the internal Catalog property to check for the /AcroForm element

/// <summary>Extensions for PdfSharp</summary>
public static class PdfSharpExtensions
{
    /// <summary>Function to access internal Catalog</summary>
    private static readonly Func<PdfDocument, PdfCatalog> GetCatalog = BuildCatalogFunc();

    /// <summary>Builds Function to access the internal Catalog</summary>
    private static Func<PdfDocument, PdfCatalog> BuildCatalogFunc()
    {
        const string CatalogProperty = "Catalog";
        var catalogProp = typeof(PdfDocument).GetProperty(
            CatalogProperty,
            BindingFlags.Instance | BindingFlags.NonPublic
        )!;
        var parameter = Expression.Parameter(typeof(PdfDocument));
        var propertyAccess = Expression.Property(parameter, catalogProp);
        var lambda = Expression.Lambda<Func<PdfDocument, PdfCatalog>>(propertyAccess, parameter);
        return lambda.Compile();
    }


    /// <summary>Check if PdfDocument has an AcroForm</summary>
    public static bool HasAcroForm(this PdfDocument document)
    {
        var catalog = GetCatalog(document);
        const string AcroFormKey = "/AcroForm";
        return catalog.Elements.ContainsKey(AcroFormKey);
    }
}

GebitMattias avatar Oct 14 '25 11:10 GebitMattias