David DeVaio
David DeVaio

Reputation: 59

ASP.Net C# Save PDF to directory

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();
    }
}

Upvotes: 5

Views: 43179

Answers (1)

Roman Marusyk
Roman Marusyk

Reputation: 24609

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();
}

Upvotes: 7

Related Questions