Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ASP.Net C# Save PDF to directory

Tags:

c#

asp.net

pdf

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();
    }
}
like image 429
David DeVaio Avatar asked Jul 19 '16 21:07

David DeVaio


People also ask

What is ASP.NET C?

ASP.NET is an open source web framework, created by Microsoft, for building modern web apps and services with . NET. ASP.NET is cross platform and runs on Linux, Windows, macOS, and Docker.

Can I use .NET with C?

. NET Framework is an object oriented programming framework meant to be used with languages that it provides bindings for. Since C is not an object oriented language it wouldn't make sense to use it with the framework.

What is ASP.NET C# used for?

ASP.NET is a server-side technology used for developing dynamic websites and web applications. ASP.NET aids developers to create web applications by using HTML, CSS, and JavaScript. ASP.NET is the latest version of Active Server Pages, which Microsoft developed to build websites.

What is .NET ASP.NET and C#?

Basically, ASP.NET is a web delivery mechanism that runs either C# or VB.NET in the background. C# is a programming language that runs ASP.NET as well as Winforms, WPF, and Silverlight.


1 Answers

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();
}
like image 147
Roman Marusyk Avatar answered Oct 22 '22 19:10

Roman Marusyk