Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create PDF on Azure blob

I am trying to create PDF on Azure blob. My code as below. I am getting issue with PDF create on blob. I am not able to create PDF getting Filestream is not supported.

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();
like image 734
Himanshu N Tatariya Avatar asked Sep 03 '26 23:09

Himanshu N Tatariya


1 Answers

FileStream is mainly used for manipulating files and since you're interested in creating PDF documents on the fly, may I suggest you use MemoryStream instead.

Take a look at the sample code below which makes use of 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);
        }
    }

If you still want to use FileStream, another thing you could do is save the file on the disk and the make use of UploadFromFile method on CloudBlockBlob to upload that file.

like image 173
Gaurav Mantri Avatar answered Sep 05 '26 14:09

Gaurav Mantri



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!