c# - ASP.Net C# 将 PDF 保存到目录

标签 c# asp.net pdf

我的网页应该如下所示: 当用户填写表单的字段并点击提交时,将为用户生成一个 PDF 文件(填充有用户输入的信息)并将该 PDF 文件保存在一个目录中。

我所拥有的是,当用户点击提交时,将为用户生成 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);

这是我在目录中保存 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();

当我运行上面的命令时,我得到一个文件:System.Byte[] 保存在 PDF 目录中,请告知我缺少什么才能将生成的 PDF 保存在目录中。

请求的每个方法的代码:

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

PDF助手代码:

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

最佳答案

PDFHelper.GeneratePDF 返回 PDF 文件的字节数组。据我了解,您需要将此 PDF 存储在本地文件夹中。在这种情况下,您可以使用

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

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

另请参阅 Can a Byte[] Array be written to a file in C#

所以,你的方法应该是这样的

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

关于c# - ASP.Net C# 将 PDF 保存到目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38468811/

相关文章:

c# - 尝试在 gridview 上更新/取消时无法加载 View 状态?

iphone - 关于iOS中PDF垂直滑动页面

c# - 获取 HTML 元素的值

c# - 如何从 Mvc 中的 Controller 调用另一个 Controller Action

jquery - 使用 JQuery 从 .NET 下拉列表中获取选定值

objective-c - cocoa PDF 页面拆分

javascript - 如何将上传的 pdf 文件传递​​给变量。 (PDF.JS)

c# - 如何拆分字符串并保留分隔符?

c# - 如何从其构造函数设置自定义异常类的 InnerException

asp.net - 在卡住列中隐藏水平滚动条