简体   繁体   English

创建PDF文件后下载

[英]Downloading PDF file after creating it

I have requirement in which i have to create a pdf file. 我有要求我必须创建一个pdf文件。 This Pdf file contains some data and it. 此Pdf文件包含一些数据及其。 Now, the main requirement is that after i create the pdf, i should be able to download it. 现在,主要要求是在创建pdf之后,我应该能够下载它。 Now the PDF is getting created, But not being able to download it. 现在正在创建PDF,但无法下载。 Please note that its an MVC application.. I am sharing the code for further reference 请注意,它是一个MVC应用程序。

public class HoldFilesController : Controller
{
    // GET: HoldFiles
    string holdpath = ConfigurationManager.AppSettings["HoldPath"].ToString();
    public ActionResult Index()
    { 
        DirectoryInfo dirInfo = new DirectoryInfo(holdpath);

        List<FileInfo> files = dirInfo.GetFiles().ToList();

        return View("Index",files);
    }

     **The above controller gets filenames from a file directory**

    public ActionResult ViewFile(string[] Name)
    {
        for (int i = 0; i < Name.Length; i++)
        {
            string filepath=holdpath + @"\" + Name[i];

            string result;
            using (StreamReader streamReader = new StreamReader(filepath))
            {
                result = streamReader.ReadToEnd();
            }

            using (System.IO.MemoryStream memoryStream = new System.IO.MemoryStream())
            {
               Document document = new Document(PageSize.A4, 10, 10, 10, 10);

               PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
               document.Open();

               Paragraph paragraph = new Paragraph();
               paragraph.Add(result);
               document.Add(paragraph);
               document.Close();
               byte[] bytes = memoryStream.ToArray();
               memoryStream.Close();
               Response.ContentType = "application/pdf";
               Response.AppendHeader("Content-Disposition", "attachment; 
filename=MyFile.pdf");
               Response.TransmitFile(Server.MapPath("~/Files/MyFile.pdf"));
               Response.End();
               Response.Close();

            }
        }

The Above controller will get a filename, read the file and create pdf and download. 上述控制器将获取文件名,读取文件并创建pdf并下载。 On debugging the code, i can see that document is created. 在调试代码时,我可以看到该文档已创建。 But having trouble in downloading it 但是下载有麻烦

You can try something like this: 您可以尝试如下操作:

private FileResult ViewFile(string[] Name)
        {
         //create your file at filePath
           byte[] fileBytes = System.IO.File.ReadAllBytes(filePath);
           return File(fileBytes, System.Net.Mime.MediaTypeNames.Application.Octet, "MyFile.pdf"));
        }

It seems that you're using a random file name to download MyFile instead of using the file you just created. 似乎您使用的是随机文件名来下载MyFile而不是使用刚创建的文件。 First of all, move the Response part outside the using and stop closing MemoryStream there, since the using block will do that for you when it finishes. 首先,将Response部分移到using之外,并在此处停止关闭MemoryStream ,因为using块将在完成时为您完成此操作。 So outside the using you should write something like: 因此,在using之外,您应该编写如下内容:

// Create New instance of FileInfo class to get the properties of the file being downloaded
FileInfo file = new FileInfo(filepath);

// Checking if file exists
if (file.Exists)
{                            
    // Clear the content of the response
    Response.ClearContent();

    // LINE1: Add the file name and attachment, which will force the open/cance/save dialog to show, to the header
    Response.AddHeader("Content-Disposition", String.Format("attachment; filename={0}", file.Name));

    // Add the file size into the response header
    Response.AddHeader("Content-Length", file.Length.ToString());

    // Set the ContentType
    Response.ContentType = ReturnFiletype(file.Extension.ToLower());

    // Write the file into the response (TransmitFile is for ASP.NET 2.0. In ASP.NET 1.1 you have to use WriteFile instead)
    Response.TransmitFile(file.FullName);

    // End the response
    Response.End();
}

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

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