将图像插入到 AZURE BLOB 存储中动态创建 PDF

Insert Image into Dynamically create PDF in AZURE BLOB Storage

我在 AZURE BLOB 存储中创建了一个动态 PDF。所有内容都写得很完美。现在我想在来自 blob 存储之一的 PDF 内容顶部添加图像。对于创建 PDF,我的代码如下:

//Parse the connection string and return a reference to the storage account.
            CloudStorageAccount storageAccount = CloudStorageAccount.Parse(CloudConfigurationManager.GetSetting("connectionstring"));

            //Create the blob client object.
            CloudBlobClient blobClient = storageAccount.CreateCloudBlobClient();

            //Get a reference to a container to use for the sample code, and create it if it does not exist.
            CloudBlobContainer container = blobClient.GetContainerReference("containername");
            container.CreateIfNotExists();

MemoryStream ms1 = new MemoryStream();
            ms1.Position = 0;
            using (ms1)
            {
                var doc1 = new iTextSharp.text.Document();
                PdfWriter writer = PdfWriter.GetInstance(doc1, ms1);
                doc1.Open();
                doc1.Add(new Paragraph("itextSharp DLL"));
                doc1.Close();
                var byteArray = ms1.ToArray();
                var blobName = "testingCREATEPDF.pdf";
                var blob = container.GetBlockBlobReference(blobName);
                blob.Properties.ContentType = "application/pdf";
                blob.UploadFromByteArray(byteArray, 0, byteArray.Length);

            }

请告诉我如何从 azure blob 在 PDF 顶部添加图像。

试试下面的代码。基本上,诀窍是将 blob 的数据作为流读取并从该流创建 iTextSharp.text.Image。拥有该对象后,您可以将其插入 PDF 文档。

private static void CreatePdf()
{
    var account = new CloudStorageAccount(new StorageCredentials(accountName, accountKey), true);
    var blobClient = account.CreateCloudBlobClient();
    var container = blobClient.GetContainerReference("pdftest");
    container.CreateIfNotExists();
    var imagesContainer = blobClient.GetContainerReference("images");
    var imageName = "Storage-blob.png";
    using (MemoryStream ms = new MemoryStream())
    {
        var doc = new iTextSharp.text.Document();
        PdfWriter writer = PdfWriter.GetInstance(doc, ms);
        doc.Open();
        doc.Add(new Paragraph("Hello World"));
        var imageBlockBlob = imagesContainer.GetBlockBlobReference(imageName);
        using (var stream = new MemoryStream())
        {
            imageBlockBlob.DownloadToStream(stream);//Read blob contents in stream.
            stream.Position = 0;//Reset the stream's position to top.
            Image img = Image.GetInstance(stream);//Create am instance of iTextSharp.text.image.
            doc.Add(img);//Add that image to the document.
        }
        doc.Close();
        var byteArray = ms.ToArray();
        var blobName = (DateTime.MaxValue.Ticks - DateTime.Now.Ticks).ToString() + ".pdf";
        var blob = container.GetBlockBlobReference(blobName);
        blob.Properties.ContentType = "application/pdf";
        blob.UploadFromByteArray(byteArray, 0, byteArray.Length);
    }
}