简体   繁体   English

使用iTextSharp链接到PDF

[英]Link to PDF using iTextSharp

There is probably a simple answer to this question but I just can't seem to find a solution. 这个问题可能有一个简单的答案,但我似乎找不到解决方法。

So I'm currently generating a PDF using iTextSharp and sending this PDF back to the user on form submit. 因此,我目前正在使用iTextSharp生成PDF,并在表单提交时将此PDF发送回给用户。 However, instead of sending this PDF in the response stream I'd like to render a link to the file ie "Thank you for submitting, click here to download the PDF". 但是,我不想在响应流中发送此PDF,而是要提供指向文件的链接,即“感谢您提交,请单击此处下载PDF”。

Looked at most iTextSharp questions on Stack but all relate to sending it via teh response stream. 查看了Stack上大多数iTextSharp问题,但所有问题都与通过响应流发送有关。

Thanks 谢谢

    [HttpPost]
    public ActionResult Index(FormCollection formCollection)
    {

        // Create PDF
        var doc = new Document();
        MemoryStream memoryStream = new MemoryStream();

        PdfWriter writer = PdfWriter.GetInstance(doc, memoryStream);

        doc.Open();
        doc.Add(new Paragraph("First Paragraph"));
        doc.Add(new Paragraph("Second Paragraph"));
        doc.Close();

        byte[] docData = memoryStream.GetBuffer(); // get the generated PDF as raw data

        // write the data to response stream and set appropriate headers:

        Response.AppendHeader("Content-Disposition", "attachment; filename=test.pdf");
        Response.ContentType = "application/pdf";
        Response.BinaryWrite(docData);

        Response.End();

        return View();

    }

This is totally independent of iTextSharp. 这完全独立于iTextSharp。

You have to store the created byte array somewhere on your server and create another action to fetch that generated data later by some kind of an ID and serve it to the user. 您必须将创建的字节数组存储在服务器上的某个位置,然后创建另一个操作以稍后通过某种ID来获取生成的数据并将其提供给用户。

You can store in in the filesystem or just in the session or TempData. 您可以存储在文件系统中,也可以存储在会话或TempData中。

public ActionResult Index(FormCollection formCollection)
{
    // Create PDF ...
    byte[] docData = memoryStream.GetBuffer(); 
    // create id and store data in Session
    string id = Guid.NewGuid().ToString();
    Session[id] = docData;
    return View("Index", id);
}

In the view Index.cshtml you set string as the modeltype and generate a donwload link: 在视图Index.cshtml ,将字符串设置为模型类型,并生成下载链接:

@model string
@Html.ActionLink("Download pdf", "Download", "Controller", new { id = Model })

And your new download action: 以及您的新下载操作:

public ActionResult Download(string id) {
    var docData = (byte[])Session[id];

    if (docData == null) 
      return HttpNotFound();

    // clear data from session
    Session[id] = null;
    // a simpler way of returning binary data with mvc
    return File(docData, "application/pdf", "test.pdf");
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM