2017-09-07 28 views
2

我想将HTML转换为PDF文件。FileContentResult的作品,但下载到字节数组不

我有以下控制器:

public ActionResult Offer([FromBody] DocumentTemplateInvoiceViewModel vm) 
    { 
     return this.Pdf(nameof(Offer), vm, "test.pdf"); 
    } 

当我在这里做一个帖子,我回来的文件,它可以打开。快乐的时光!

但是,如果我尝试做以下操作:

var termsClient = new RestClient(ConfigurationManager.AppSettings["HostingUrl"]); 
    var termsRequest = new RestRequest("/Document/Offer", Method.POST); 
    termsRequest.AddJsonBody(vm); 
    var json = JsonConvert.SerializeObject(vm); 
    var termsBytes = termsClient.DownloadData(termsRequest); 
    File.WriteAllBytes("LOCALPATH",termsBytes); 

文件损坏,我无法打开PDF。它有一些大小,所以它存储了一些字节。可能只是没有正确存储:D

任何想法我做错了什么?为什么我的控制器的FileContentResult工作正常,但是当我下载数据时它已损坏?

+0

检查原始请求。这两个请求有可能要求两种不同的内容类型。 – Nkosi

+2

由于问题的解决方式对未来的其他人不太可能有帮助,因此我退还了您的赏金,并将其视为无法重现。如果您同意这里没有任何对他人有用的内容,请随时删除。 (你应该可以自己删除它,你可能不得不不接受你自己的答案,我不记得系统允许的东西)。 –

回答

0

事实我是个笨蛋,问题是完全不同的。端点只是返回一个404错误,它刚刚下载并包装到一个文件中(显然这给出了一个损坏的PDF文件)。

因此,此代码完美工作。看着Fiddler的请求很快就显示出这个问题。

+0

是的,可以发生。 :)因此*检查原始请求建议*。活到老,学到老。我去过那儿 – Nkosi

0

你有你的问题标记为MVC所以我会尝试作为一个MVC应用程序作出回应。

REST对象似乎表示WEB.API,但也许我错了。 :)

如果你在谈论FileContentResult,那么我建议放入ContentType。

var contentType = System.Net.Mime.MediaTypeNames.Application.Pdf; 

然后加载FileContentResult这样的:

var fcr = new FileContentResult(ms.ToArray(), contentType); //NOTE: Using a File Stream Result will not work. 
fcr.FileDownloadName = FileName; 

我看到你正在使用的PDF生成所以这里是我用来生成FileContentResult为PDF的例子:

public FileContentResult CreatePdfFileContentResult() 
    { 
     var contentType = System.Net.Mime.MediaTypeNames.Application.Pdf; 
     using (MemoryStream ms = new MemoryStream()) 
     { 
      // Create an instance of the document class which represents the PDF document itself. 
      Document document = new Document(PageSize.A4, 25, 25, 30, 30); 
      // Create an instance to the PDF file by creating an instance of the PDF 
      // Writer class using the document and the filestrem in the constructor. 
      PdfWriter writer = PdfWriter.GetInstance(document, ms); 

      if (OnPdfMetaInformationAdd != null) 
       OnPdfMetaInformationAdd(document, DataSource); 

      // Open the document to enable you to write to the document 
      document.Open(); 

      if (OnPdfContentAdd != null) 
       OnPdfContentAdd(document, DataSource); 
      else throw new NotImplementedException("OnPdfContentAdd event not defined"); 

      // Close the document 
      document.Close(); 
      // Close the writer instance 
      writer.Close(); 

      var fcr = new FileContentResult(ms.ToArray(), contentType); //NOTE: Using a File Stream Result will not work. 
      fcr.FileDownloadName = FileName;     
      return fcr; 
     } 
    }