我正在尝试在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();

最佳答案

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方法上传该文件。

10-06 02:38