在Azure blob上创建PDF

时间:2015-06-27 11:19:19

标签: azure azure-storage-blobs

我正在尝试在Azure blob上创建PDF。我的代码如下。我在blob上遇到PDF创建问题。我无法创建PDF,因此不支持Filestream。

FileStream fs = new FileStream("Chapter1_Example1.pdf", FileMode.Create, FileAccess.Write, FileShare.None);
            iTextSharp.text.Document doc = new iTextSharp.text.Document();

            PdfWriter writer = PdfWriter.GetInstance(doc, fs);
            doc.Open();
            doc.Add(new Paragraph("Hello World"));


            var permissions = container.GetPermissions();
            permissions.PublicAccess = BlobContainerPublicAccessType.Blob;
            container.SetPermissions(permissions);
            string uniqueBlobName = string.Format("rewhizzdocuments/{0}", "helloworld.pdf");
            CloudBlockBlob blob = container.GetBlockBlobReference(uniqueBlobName);
            blob.Properties.ContentType = "application/pdf";
            blob.UploadFromStream(fs);


            doc.Close();

2 个答案:

答案 0 :(得分:4)

FileStream主要用于处理文件,因为您有兴趣动态创建PDF文档,我建议您改用MemoryStream

看看下面的示例代码,它使用了MemoryStream

    private static void CreatePdf()
    {
        var account = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
        var blobClient = account.CreateCloudBlobClient();
        var container = blobClient.GetContainerReference("pdftest");
        using (MemoryStream ms = new MemoryStream())
        {
            using (var doc = new iTextSharp.text.Document())
            {
                PdfWriter writer = PdfWriter.GetInstance(doc, ms);
                doc.Open();
                doc.Add(new Paragraph("Hello World"));
            }
            var byteArray = ms.ToArray();
            var blobName = "hello-world.pdf";
            var blob = container.GetBlockBlobReference(blobName);
            blob.Properties.ContentType = "application/pdf";
            blob.UploadFromByteArray(byteArray, 0, byteArray.Length);
        }
    }

如果您仍想使用FileStream,则可以执行的另一项操作是将文件保存在磁盘上,并在UploadFromFile上使用CloudBlockBlob方法上传该文件。< / p>

答案 1 :(得分:0)

请先调用doc.Close(),然后再调用blob.UploadFromFile(&#34; Chapter1_Example1.pdf&#34;)。

另一种可能的解决方案是:首先调用doc.Close(),然后设置fs.Position = 0L,最后设置blob.UploadFromStream(fs)。 (如果doc.Close()会自动触发FileStream的处理,它可能不是一个有效的解决方案,我不能确定,因为我不熟悉iText。