MVCRazorToPDF将PDF保存到位置或Blob然后下载

时间:2014-09-30 13:15:25

标签: asp.net-mvc-4 mvcrazortopdf

以下是我的代码:

 public class ActionDownloadAttribute : ActionFilterAttribute 
 {
       public override void OnResultExecuted(ResultExecutedContext filterContext)
       {
             filterContext.HttpContext.Response.AddHeader("content-disposition", "attachment; filename=" + "Report.pdf");
             base.OnResultExecuted(filterContext);
       }
 }


[ActionDownload]
 public ActionResult GeneratePdf()
 {
       List<Comment> comments = null;
        using (var db = new CandidateEntities())
        {
            comments = db.Comments.ToList();
        }
        return new PdfActionResult("GeneratePdf", comments);
 }

上面的代码给出了PDF文件供下载。但我想在下载之前将其保存(自动)到特定路径或Blob。

任何人都可以帮助我吗?

2 个答案:

答案 0 :(得分:1)

当我最初看到我的答案时,它并没有真正带来很多价值。所以我会尝试扩展。

不是异步

首先,我和你有完全相同的控制器。然后我使用restsharp来调用该URL

        var client = new RestClient("http://some.url.com");

        var request = new RestRequest("mvc/GeneratePDF", Method.GET);
        // execute the request
        RestResponse response = (RestResponse)client.Execute(request);

        // Zwracamy byte[] ktory jest naszym plikiem PDF
        return response;

现在,如果您查看 response.RawBytes ,可以使用以下方法将字节数组直接上传到Azure :)

我调用我的两种方法之一来上传byte []或从流

 public static class AzureStorage
{
    /// <summary>
    /// Metoda zajmujaca sie uploadem do Azure
    /// </summary>
    public static string _uploadToAzureBlob(byte[] arrPDF, string azureContainer, string filename)
    {
        // Retrieve connection string
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConn"));
        // Create blob client
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        // Retrieve reference to a previously created container.
        CloudBlobContainer container = blobClient.GetContainerReference(azureContainer);
        // Create object blob 
        CloudBlockBlob blob = container.GetBlockBlobReference(filename);
        // Upload
        blob.UploadFromByteArray(arrPDF, 0, arrPDF.Length);

        return blob.Uri.ToString();
    }

    /// <summary>
    /// Metoda zajmujaca sie uploadem do Azure
    /// </summary>
    public static string _uploadToAzureBlob(Stream iostream, string azureContainer, string filename, bool ApplyReadPermissions = true)
    {
        // Retrieve connection string
        CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("StorageConn"));
        // Create blob client
        CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();
        // Retrieve reference to a previously created container.
        CloudBlobContainer container = blobClient.GetContainerReference(azureContainer);

        // Create container if it does not exist
        container.CreateIfNotExists();

        // Create object blob 
        CloudBlockBlob blob = container.GetBlockBlobReference(filename);

        iostream.Position = 0;//Move the pointer to the start of stream..

        using (var fileStream = iostream)
        {
            blob.UploadFromStream(fileStream);
        }

        // Here we need to share the URL for reading the barcode! Otherwise we dont have access to it
        if (ApplyReadPermissions)
        {
            var builder = new UriBuilder(blob.Uri);
            builder.Query = blob.GetSharedAccessSignature(
                new SharedAccessBlobPolicy
                {
                    Permissions = SharedAccessBlobPermissions.Read,
                    SharedAccessStartTime = new DateTimeOffset(DateTime.UtcNow.AddMinutes(-5)),
                    SharedAccessExpiryTime = new DateTimeOffset(DateTime.UtcNow.AddMinutes(5))
                }).TrimStart('?');

            var x = builder.Uri.ToString();

            return x;
        }

        return null;
    }
}

如果这有帮助,请告诉我。它在我的天蓝色环境中适合我。我有一个webjob生成这些文件并自动保存在blob上。

已更新:异步

如果您要重写那些上传到Azure的方法为Async,那么使用下面的内容可以让您进行以下调用:

    public async Task<ActionResult> asyncPDF()
    {
        return await AzureStorage._uploadToAzureBlob( ControllerContext.GeneratePdf(objModel, "VIEW_NAME") ) ;
    }

我将更详细地测试该方法以确认其行为。

非常欢迎评论:D

答案 1 :(得分:1)

请检查此示例中的方法SaveToAppData:

https://github.com/andyhutch77/MvcRazorToPdf/blob/master/MvcRazorToPdfExample/Controllers/PdfController.cs

它使用ControllerContext中的GeneratePdf方法来实现:

        byte[] pdfOutput = ControllerContext.GeneratePdf(model, "IndexWithAccessToDocumentAndWriter");
        string fullPath = Server.MapPath("~/App_Data/FreshlyMade.pdf");

        if (SysIO.File.Exists(fullPath))
        {
            SysIO.File.Delete(fullPath);
        }
        SysIO.File.WriteAllBytes(fullPath, pdfOutput);