Change a detachable PDF field

Asked

Viewed 1,033 times

2

I’m working on MVC 4 and installed the iTextSharp to create PDF’s, until everything well. But what I am doing is replicating a PDF that already exists, to fill the respective fields required in this created PDF.

Now arises the doubt:

The PDF I’m replicating has those fields called detachable, That is, we can open the PDF and write to them as if we were editing the PDF. It is possible from iTextSharp to open this same PDF file, detect these fields and write to them from the controller?

2 answers

1

Yes, it is possible! You need to use the namespace iTextSharp.text.pdf. camposDict is a IDictionary traditional.

Follow the implementation I use:

public string PDFReplace(
               string path, // PATH do arquivo
               string arquivo, // NOME do arquivo com extensão
               object camposDict // IDictionary
               )
{
    string pathPdf = string.Empty;
    PdfReader pdf = new PdfReader(@path.ToString());
    MemoryStream outStream = new MemoryStream();
    PdfStamper stamper = new PdfStamper(pdf, outStream);

    AcroFields fields = stamper.AcroFields;

    foreach (DictionaryEntry de in (Hashtable)camposDict)
    {
        string Key = (string)de.Key;
        string value = de.Value.ToString();

        fields.SetField(Key, value);
    }

    stamper.FormFlattening = true;
    stamper.Close();
    pdf.Close();

    string urlPasta = path.ToString().Substring(0, path.ToString().LastIndexOf("\\"));

    File.WriteAllBytes(urlPasta + "\\" + arquivo.ToString().ToUpper(), outStream.ToArray());
    return urlPasta + "\\" + arquivo.ToString().ToUpper();
}

Update

An addendum: the IDictionary should be composed by the name of the PDF dynamic field (yes, they need to be named) and the respective value of it.

  • that camposDict is being received in the function. What value do I pass there? It is the absolute filename (path + filename) ??

  • No, it’s a dictionary, use as Hashtable where the key is the PDF field name!

  • Yeah, there’s a problem. The client gave me the PDF without details. How do I know the name of the fields? I’m here looking in Foxit and I can’t find anything that tells me the name of the fields

  • I filled in the form and exported the data to a .txt. Will the output displayed be the name of the fields in the PDF? Result: empresa de origem 1 empresa de origem 2 empresa de origem 3 empresa de origem 4 empresa de origem 5 empresa de origem 6 LocalData Assinatura Na qualidade de tradutor públ
11 22 33 44 55 66

  • If you open a PDF with titles in Adobe PDF Reader, it displays! But to edit them you would need adobe Creator or equivalent.

  • Man, I don’t know... maybe they are! It’s worth the test!

  • By creating the string urlPasta get the error Length cannot be less than zero.. That’s because?

  • Its variable path should end with backslash (you can change according to your need). For me it was so because it used a network path. The purpose of this is to sanitize the bars, I would have solved it differently than we did when this code was created.

  • Yes, I’m done correcting. It’s not writing in the headlines. I’m doing something like:Hashtable campos = new Hashtable(); campos[1] = "empresa de origem 1"; campos[2] = "empresa de origem 2";

 foreach (DictionaryEntry de in (Hashtable)campos)
 {
 string Key = de.Key.ToString(); string value = "teste 1 !!!"; fields.SetField(Key, value);
 }

  • Well, as I said, I suspect the camps should be named

  • I don’t think I know the name of the fields. I will draw the pdf :|

Show 6 more comments

1


Friend, we will better understand the application of your system... I could not understand what you need, so we can give a better answer.

Will you have a Form, or contract, or something like that that needs to be filled out by multiple customers or employees? Through the right system?

Does the content of this PDF constantly change? Are there several types of forms? (If both are negative you canif you put its contents fixed in your code or save the text in a table from a screen where the user who mounts the form type and click on a button that adds a gap and so on and when it comes to generating the PDF within the application you replace these Tags by fields.)

UPDATE:

I found an example that might help you!

//Read all 'Form values/keys' from an existing multi-page PDF document
public void ReadPDFformDataPageWise()
{
PdfReader reader = new PdfReader(Server.MapPath(P_InputStream3));
AcroFields form = reader.AcroFields;
try
{
for (int page = 1; page <= reader.NumberOfPages; page++)
{
    foreach (KeyValuePair<string, AcroFields.Item> kvp in form.Fields)
    {
        switch (form.GetFieldType(kvp.Key))
        {
            case AcroFields.FIELD_TYPE_CHECKBOX:
            case AcroFields.FIELD_TYPE_COMBO:
            case AcroFields.FIELD_TYPE_LIST:
            case AcroFields.FIELD_TYPE_RADIOBUTTON:
            case AcroFields.FIELD_TYPE_NONE:
            case AcroFields.FIELD_TYPE_PUSHBUTTON:
            case AcroFields.FIELD_TYPE_SIGNATURE:
            case AcroFields.FIELD_TYPE_TEXT:
                int fileType = form.GetFieldType(kvp.Key);
                string fieldValue = form.GetField(kvp.Key);
                string translatedFileName = form.GetTranslatedFieldName(kvp.Key);
                break;
        }
    }
}
}
catch
{
}
finally
{
    reader.Close();
}
}

This and other examples of how to use iTextSharp you find at this link

  • what I wanted to do was open a file in the controller from iTextSharp, and detect the detachable fields that the PDF has, so I could fill them with data that would fetch the database.

  • What does this method do is not scan and recover these fields? case AcroFields.FIELD_TYPE_TEXT: wouldn’t be an editable field? : int fileType, string fieldValue and string translatedFileName are satisfactory to your need, if yes just change the method or create other methods to complement your intention. Have you looked at the link I sent you? It’s in English but there’s a lot of stuff. http://simpledotnetsolutions.wordpress.com/2012/04/itextsharp-few-c-examples/

  • Yes, I’ve been looking and I can really get the PDF fields. On the link you gave, you can write in pfd. Thank you

Browser other questions tagged

You are not signed in. Login or sign up in order to post.