2017-09-07 31 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; 
     } 
    }