locked
Dictionary loop error RRS feed

  • Question

  • User1510859543 posted

    I found some sample code to read fields in a PDF file using iTextSharp.dll that I really want to get to work. However, in VS I am getting the error "Value of type 'KeyValuePair(Of String, AcroFields.Item) cannot be converted to 'DictionaryEntry'

    The error is on the line "For Each de As DictionaryEntry In pdfReader.AcroFields.Fields"

    Below is my code in VB followed by the code I converted from C#.

        Private Sub ListFieldNames()
            Dim pdfTemplate As String = "c:\Temp\PDF\fw4.pdf"
            'Me.Text += " - " & pdfTemplate
            Dim pdfReader As PdfReader = New PdfReader(pdfTemplate)
            Dim sb As StringBuilder = New StringBuilder()
    
            For Each de As DictionaryEntry In pdfReader.AcroFields.Fields
                sb.Append(de.Key.ToString() + Environment.NewLine)
            Next
    
            TextBox1.Text = sb.ToString()
    
        End Sub
    
    /// <summary>  
    /// List all of the form fields into a textbox.  The  
    /// form fields identified can be used to map each of the  
    /// fields in a PDF.  
    /// </summary>  
    private void ListFieldNames()  
    {  
        string pdfTemplate = @"c:\Temp\PDF\fw4.pdf";  
        // title the form  
        this.Text += " - " + pdfTemplate;  
        // create a new PDF reader based on the PDF template document  
        PdfReader pdfReader = new PdfReader(pdfTemplate);  
        // create and populate a string builder with each of the  
        // field names available in the subject PDF  
        StringBuilder sb = new StringBuilder();  
        foreach (DictionaryEntry de in pdfReader.AcroFields.Fields)  
        {  
            sb.Append(de.Key.ToString() + Environment.NewLine);  
        }  
        // Write the string builder's content to the form's textbox  
        textBox1.Text = sb.ToString();  
        textBox1.SelectionStart = 0;  
    } 

    Thursday, September 12, 2019 9:31 PM

Answers

  • User665608656 posted

    Hi dlchase,

    However, in VS I am getting the error "Value of type 'KeyValuePair(Of String, AcroFields.Item) cannot be converted to 'DictionaryEntry'

    This error shows that the type of pdfReader.AcroFields.Fields is different from the DictionaryEntry type.

    There is one of the most convenient and commonly used var types to replace DictionaryEntry, var is an implicitly typed local variable which is strongly typed just as if you had declared the type you, but the compiler determines the type.

    Or, you can use KeyValuePair<string, AcroFields.Item> to replace DictionaryEntry.

    You can refer to this link : How do I enumerate all the fields in a PDF file in ITextSharp

    Best Regards,

    YongQing.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Friday, September 13, 2019 5:32 AM