【问题标题】:itextsharp form name and saving pdfitextsharp 表单名称和保存 pdf
【发布时间】:2014-08-19 18:29:29
【问题描述】:

我在 ASP.NET 中使用 itextsharp。我们使用从我们的一个在线表格中获取的字段填充 PDF。我需要改变我们处理文档的方式——我们需要能够使用某些字段作为文档的名称(firstname-lastname.pdf),并将该 PDF 保存到一个目录中。这是我现在使用的代码:

    PdfStamper ps = null;        
        DataTable dt = BindData();
        if (dt.Rows.Count > 0)
        {                
            PdfReader r = new PdfReader(new RandomAccessFileOrArray("http://www.example.com/Documents/ppd-certificate.pdf"), null);
            ps = new PdfStamper(r, Response.OutputStream);

            AcroFields af = ps.AcroFields;

            af.SetField("fullName", dt.Rows[0]["fullName"].ToString());
            af.SetField("presentationTitle", dt.Rows[0]["presentationTitle"].ToString());
            af.SetField("presenterName", dt.Rows[0]["presenterFullName"].ToString());
            af.SetField("date", Convert.ToDateTime(dt.Rows[0]["date"]).ToString("MM/dd/yyyy"));

            ps.FormFlattening = true;

            ps.Close();
        }

【问题讨论】:

  • 所以不是将 PDF 发送到Response.OutputStream,而是要写入磁盘?这是你的问题吗?
  • 目前上述代码将 PDF 打印到浏览器。但我想将 PDF 发送到网络驱动器上的目录。

标签: pdf itextsharp


【解决方案1】:

PdfStamperPdfWriter 都使用通用的Stream 类,因此您可以使用FileStreamMemoryStream 来代替Response.OutputStream

此示例直接写入磁盘。把testFile设置成你想要的,我这里用的是桌面

//Your file path here:
var testFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");
using (var fs = new FileStream(testFile, FileMode.Create, FileAccess.Write, FileShare.None)) {
    PdfReader r = new PdfReader(new RandomAccessFileOrArray("http://www.example.com/Documents/ppd-certificate.pdf"), null);
    var ps = new PdfStamper(r, fs);
    //..code
}

下一个示例是我的首选方法。它创建一个MemoryStream,然后在其中创建一个 PDF,最后抓取原始字节。一旦获得原始字节,您就可以将它们写入磁盘和Response.BinaryWrite()

byte[] bytes;
using (var ms = new MemoryStream()) {
    PdfReader r = new PdfReader(new RandomAccessFileOrArray("http://www.example.com/Documents/ppd-certificate.pdf"), null);
    var ps = new PdfStamper(r, ms);
    //..code

    bytes = ms.ToArray();
}

//Your file path here:
var testFile = System.IO.Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "test.pdf");

//Write to disk
System.IO.File.WriteAllBytes(testFile, bytes);

//Send to HTTP client
Response.BinaryWrite(bytes);

【讨论】:

  • 谢谢,我会试试这个。是否可以使用表单中的字段保存文件,即 firstname-lastname.pdf?
  • 是的,在上述任一示例中,只需将 test 文件替换为您的适当路径,并使用您想要的任何逻辑来命名文件。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2019-10-10
  • 1970-01-01
  • 2011-09-02
  • 2015-07-27
  • 2020-11-25
  • 2011-01-08
  • 1970-01-01
相关资源
最近更新 更多