【问题标题】:Open save as window with iTextSharp使用 iTextSharp 打开另存为窗口
【发布时间】:2013-11-27 15:42:13
【问题描述】:

使用 iTextSharp 将网页保存为 PDF 时,有没有办法打开另存为窗口?现在我只是将它保存到一个集合文件中。

var pdfDoc = new Document();

const string folderPath = "C:\\SG-ListingPDFs\\";

bool isExists = Directory.Exists(folderPath);

if (!isExists)
    Directory.CreateDirectory(folderPath);

var writer = PdfWriter.GetInstance(pdfDoc, new FileStream("C:\\SG-ListingPDFs\\" + detailsViewModel.ListingNumber + ".pdf", FileMode.Create));
pdfDoc.Open();

....Code Here

pdfDoc.Add(table);

TempData["SavedPdF"] = true;
pdfDoc.Close();

【问题讨论】:

标签: c# asp.net asp.net-mvc asp.net-mvc-4 itextsharp


【解决方案1】:

您需要有一个 ActionResult 方法来返回一个文件并设置适当的请求标头。

public ActionResult Pdf()
{
    Response.AddHeader("Content-Disposition", "attachment;filename=YourFile.pdf");
    return File(yourPdfFile, "application/octet-stream");
}

File() 有一些重载,它们采用byte[]System.IO.Stream 或磁盘上实际文件的路径。我对 iTextSharp 不太熟悉,因此无法为您提供更多帮助,但这应该会让您走上正轨。

如果我没记错的话,特定浏览器(我想是 IE)中需要标头才能弹出另存为对话框。

【讨论】:

    【解决方案2】:

    我会将流创建为引用变量,即

    var aFileName = string.Format("{0}.{1}", detailsViewModel.ListingNumber + "pdf";
    var aStream =  new FileStream("C:\\SG-ListingPDFs\\" + aFileName);
    

    然后像这样将它传递给 get 实例:

    var writer = PdfWriter.GetInstance(pdfDoc, aStream , FileMode.Create));
    

    然后从您的控制器返回这样的流作为FileResult

    public ActionResult SaveFile()
    {   
        // processing to get the file etc....
    
        return File(filePath, aStream , aFileName);
    }
    

    上面的重要部分是aFileName 参数,这是fileNameDownload 参数,它可以作为可下载文件打开。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-13
      • 1970-01-01
      • 2013-11-17
      • 2021-07-09
      相关资源
      最近更新 更多