C# 从流中读取PDF时未找到PDF标头签名,

C# 从流中读取PDF时未找到PDF标头签名,,c#,itext,azure-storage-blobs,C#,Itext,Azure Storage Blobs,我正在从blob容器下载文件并保存到流中,同时尝试读取pdf //creating a Cloud Storage instance CloudStorageAccount StorageAccount = CloudStorageAccount.Parse(connectionstring); //Creating a Client to operate on blob CloudBlobClient blobClient

我正在从blob容器下载文件并保存到流中,同时尝试读取pdf

            //creating a Cloud Storage instance
        CloudStorageAccount StorageAccount = CloudStorageAccount.Parse(connectionstring);
        //Creating a Client to operate on blob
        CloudBlobClient blobClient = StorageAccount.CreateCloudBlobClient();
        // fetching the container based on name
        CloudBlobContainer container = blobClient.GetContainerReference(containerName);
        //Get a reference to a blob within the container.
        CloudBlockBlob blob = container.GetBlockBlobReference(fileName);
        var memStream = new MemoryStream();
        blob.DownloadToStream(memStream);
        try
        {
            PdfReader reader = new PdfReader(memStream);
        }
        catch(Exception ex)
        {

        }

异常:未找到PDF标题签名。

通过注释进行故障排除后,原因很明显,这一行:

blob.DownloadToStream(memStream);
memStream.Position = 0;
将流定位在下载内容之后

然后,在构建pdf阅读器对象时,它希望从当前位置找到pdf文件

这是一个常见的问题,当处理流时,首先向其写入内容,然后尝试读取该内容,如果需要,必须记住重新定位流

在这种情况下,假设流中只有pdf,解决方案是在尝试读取pdf文件之前将流重新定位回起始位置:

添加此行:

blob.DownloadToStream(memStream);
memStream.Position = 0;
在下载之后但在构建读取器以重新定位之前

以下是此区域中的代码:

blob.DownloadToStream(memStream);
memStream.Position = 0; // <----------------------------------- add this line
try
{
    PdfReader reader = new PdfReader(memStream);
blob.DownloadToStream(memStream);

memStream.Position=0;//那么,你确定它是pdf文件吗?您是否尝试将其保存到本地文件并检查其内容?是的,我尝试将其保存到本地&它可以工作。但不确定它为什么不能与stream一起工作。另一个可能的原因可能是在调用
DownloadToStream
后,流位置放在下载内容之后,而
PdfReader
希望能够从当前所在的位置读取Pdf。尝试在
DownloadToStream
之后添加此行代码:
memStream.Position=0工作!我怎样才能把这个添加为一个答案,这样它也会帮助其他人呢?我会发布一个答案。