5

I have a webpage that should work as the following: When a user fills the form's fields and hits submit, a PDF file will be generated for the user (filled with the info the user entered) and that PDF file gets saved in a directory.

What I have is, when the user hits Submit the PDF gets generated for the user:

        var pdfPath = Path.Combine(Server.MapPath(path_name));
        String file_name_pdf = "Test.pdf";
        var pdfContents = PDFHelper.GeneratePDF(pdfPath, formFieldMap);
        PDFHelper.ReturnPDF(pdfContents, file_name_pdf);

Here is my attempt for saving the PDF in the directory,

    var pdfPath = Path.Combine(Server.MapPath(path_name));
    var formFieldMap = PDFHelper.GetFormFieldNames(pdfPath);

    string username = "Test";
    string password = "12345";      
    String file_name_pdf = "Test.pdf";

    var pdfContents = PDFHelper.GeneratePDF(pdfPath, formFieldMap);
    WebRequest request = WebRequest.Create(Server.MapPath("~/PDF/" + pdfContents));
    request.Method = WebRequestMethods.Ftp.UploadFile;

    request.Credentials = new NetworkCredential(username, password);
    Stream reqStream = request.GetRequestStream();
    reqStream.Close();

When I ran the above I get a file: System.Byte[] Saved in the PDF directory, please advise what am I missing to get the generated PDF get saved in the directory.

The code for each Method as requested:

    protected void generate_pdf()
    {
            String path_name = "~/Forms/Form1.pdf";
            var pdfPath = Path.Combine(Server.MapPath(path_name));
            String file_name_pdf = "Test.pdf";
            var pdfContents = PDFHelper.GeneratePDF(pdfPath, formFieldMap);
            PDFHelper.ReturnPDF(pdfContents, file_name_pdf);
    }

    protected void save_pdf()
    {
           String path_name = "~/PDF/";
           var pdfPath = Path.Combine(Server.MapPath(path_name));
           var formFieldMap = PDFHelper.GetFormFieldNames(pdfPath);

           string username = "Test";
           string password = "12345";      
           String file_name_pdf = "Test.pdf";

           var pdfContents = PDFHelper.GeneratePDF(pdfPath, formFieldMap);
           WebRequest request = WebRequest.Create(Server.MapPath("~/PDF/" + pdfContents));
           request.Method = WebRequestMethods.Ftp.UploadFile;

           request.Credentials = new NetworkCredential(username, password);
           Stream reqStream = request.GetRequestStream();
           reqStream.Close();
     }

PDFHelper code:

using System;
using System.Collections.Generic;
using System.Collections;
using System.Linq;
using System.Web;
using System.IO;
using iTextSharp.text.pdf;

public class PDFHelper
{
    public static Dictionary<string, string> GetFormFieldNames(string pdfPath)
    {
        var fields = new Dictionary<string, string>();

        var reader = new PdfReader(pdfPath);
        foreach (DictionaryEntry entry in reader.AcroFields.Fields)
            fields.Add(entry.Key.ToString(), string.Empty);
        reader.Close();

        return fields;
    }

    public static byte[] GeneratePDF(string pdfPath, Dictionary<string, string> 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 static string GetExportValue(AcroFields.Item item)
    {
        var valueDict = item.GetValue(0);
        var appearanceDict = valueDict.GetAsDict(PdfName.AP);

        if (appearanceDict != null)
        {
            var normalAppearances = appearanceDict.GetAsDict(PdfName.N);
             if (normalAppearances != null)
            {
                foreach (var curKey in normalAppearances.Keys)
                    if (!PdfName.OFF.Equals(curKey))
                        return curKey.ToString().Substring(1); // string will have a leading '/' character, so remove it!
            }
        }

        var curVal = valueDict.GetAsName(PdfName.AS);
        if (curVal != null)
            return curVal.ToString().Substring(1);
        else
            return string.Empty;
    }

    public static void ReturnPDF(byte[] contents)
    {
        ReturnPDF(contents, null);
    }

    public static void ReturnPDF(byte[] contents, string attachmentFilename)
    {
        var response = HttpContext.Current.Response;

        if (!string.IsNullOrEmpty(attachmentFilename))
            response.AddHeader("Content-Disposition", "attachment; filename=" + attachmentFilename);

        response.ContentType = "application/pdf";
        response.BinaryWrite(contents);
        response.End();
    }
}
David DeVaio
  • 59
  • 1
  • 1
  • 6
  • You need to post all the code. Where is the source for PDFHelper? – Jon Jul 19 '16 at 21:31
  • 1
    When you say "I get a file: System.Byte[]" do you mean the contents of the file is the string "System.Byte[]"? – agriffin Jul 19 '16 at 21:36
  • No sir, the file that gets saved in the directory is called: System.Byte[] @AndrewGriffin – David DeVaio Jul 19 '16 at 22:15
  • @Mangist Sure, I have updated the code to include that. Thank you. – David DeVaio Jul 19 '16 at 22:16
  • Where do you use `PDFHelper.ReturnPDF(pdfContents, file_name_pdf);`? – Roman Marusyk Jul 19 '16 at 22:22
  • I use it to generate the file for the user. I do not use it to save the PDF file to the directory. Thank you for asking. @MegaTron – David DeVaio Jul 19 '16 at 22:24
  • Can you post all code of each methods? Do you use iTextSharp? – Roman Marusyk Jul 19 '16 at 22:26
  • @MegaTron Sure, I posted the entire code for the two methods. No, I am not using iTextSharp. I take the PDF from a saved location, add the info to it from the fields then I save this new pdf file to the PDF directory. – David DeVaio Jul 19 '16 at 22:36
  • @DavidDeVaio You wrote: When I ran the above I get a file: System.Byte[] Saved in the PDF directory, please advise what am I missing to get the generated PDF get saved in the directory. What do you mean? Your PFD is saved with name System.Byte[] or it doesn't save? Also I do not know what PDFHelper do, because you do not want to post all code. So, how can we help you? – Roman Marusyk Jul 19 '16 at 22:55
  • @MegaTron a file called System.Byte[] shows up in the PDF directory, it is not a pdf file.. I feel it is sort of an error thing. Sure, I will post the PDFHelper code. – David DeVaio Jul 19 '16 at 23:00
  • @MegaTron Thank you for looking into this. – David DeVaio Jul 19 '16 at 23:03

1 Answers1

7

The PDFHelper.GeneratePDF is returning array of bytes of PDF file. As I understood, ater that you need to store this PDF in local folder. In that case you can use

using (var stream = File.Create(Path.Combine(pdfPath, file_name_pdf)))
{
      stream.Write(pdfContents, 0, pdfContents.Length);
}

or

File.WriteAllBytes(Path.Combine(pdfPath, file_name_pdf), pdfContents)

Also, please see Can a Byte[] Array be written to a file in C#

So, your method should looks like that

protected void save_pdf()
{
   String path_name = "~/PDF/";
   var pdfPath = Path.Combine(Server.MapPath(path_name));
   var formFieldMap = PDFHelper.GetFormFieldNames(pdfPath);

   string username = "Test";
   string password = "12345";      
   String file_name_pdf = "Test.pdf";

   var pdfContents = PDFHelper.GeneratePDF(pdfPath, formFieldMap);

   File.WriteAllBytes(Path.Combine(pdfPath, file_name_pdf), pdfContents);

   WebRequest request = WebRequest.Create(Server.MapPath("~/PDF/" + pdfContents));
   request.Method = WebRequestMethods.Ftp.UploadFile;

   request.Credentials = new NetworkCredential(username, password);
   Stream reqStream = request.GetRequestStream();
   reqStream.Close();
}
Community
  • 1
  • 1
Roman Marusyk
  • 23,328
  • 24
  • 73
  • 116
  • 1
    thank you so much for your help, it worked perfectly. I accepted the answer but I am still under the 15 reputation to mark it as "Useful". To everybody who ran into the same issue, the answer from MegaTron solved it for me. – David DeVaio Jul 20 '16 at 19:19
  • Thanks. Glad to have been of help – Roman Marusyk Jul 20 '16 at 21:17