Best way to create/fill-in printed forms and pdfs?

前端 未结 8 693
没有蜡笔的小新
没有蜡笔的小新 2021-02-02 15:17

We have a C# application that must print complex forms. Things like multi-page government compliance forms that must be in a specific format. We can get PDF copies of these fo

8条回答
  •  时光取名叫无心
    2021-02-02 16:04

    Try with this:

    string Filepath = Server.MapPath("/AOF.pdf");
    var pdfpath = Path.Combine(Filepath, "");
    var Formcontent = ListFieldNames(Filepath);
    Formcontent["Name_txt"] =  "T.Test" ;  FillForm(Formcontent); //  var pdfContents = FillForm(pdfpath, Formcontent);
    
    public Dictionary ListFieldNames(string Filepath)
    {
        //PdfReader pdfReader = new PdfReader(pdfTemplate);
        //StringBuilder sb = new StringBuilder();
        //foreach(DictionaryEntry de in pdfReader.AcroFields.Fields)
        //{
        //    sb.Append(de.Key.ToString() + Environment.NewLine);
        //}
        var Fileds = new Dictionary();
        PdfReader pdfReader = new PdfReader(Filepath);
        var reader = new PdfReader(pdfReader);
        foreach (var entry in reader.AcroFields.Fields)
            Fileds.Add(entry.Key.ToString(), string.Empty);
        reader.Close();
        return Fileds;
    }
    
    public byte[] FillForm(string pdfPath, Dictionary formFieldMap)
    {
        var output = new MemoryStream();
        var reader = new PdfReader(pdfPath);
        var stamper = new PdfStamper(reader, output);
        var formFields = stamper.AcroFields;
        foreach (var fieldName in formFieldMap.Keys)
            formFields.SetField(fieldName, formFieldMap[fieldName]);
        stamper.FormFlattening = true;
        stamper.Close();
        reader.Close();
        return output.ToArray();
    }
    
    public void FillForm(Dictionary Formfiledmap)
    {
        string pdfTemplate = Server.MapPath("/AOF.pdf");
        string newFile = @"C:\Users\USer\Desktop\completed_fw4.pdf";
        PdfReader pdfReader = new PdfReader(pdfTemplate);
        PdfStamper pdfStamper = new PdfStamper(pdfReader, new FileStream(newFile, FileMode.Create));
        AcroFields pdfFormFields = pdfStamper.AcroFields;
        foreach (var fieldName in Formfiledmap.Keys)
            pdfFormFields.SetField(fieldName, Formfiledmap[fieldName]);
        pdfStamper.FormFlattening = true;
        pdfStamper.Close();
    }
    

提交回复
热议问题