Read and display a PDF inside a zipped folder without extracting it

Asked

Viewed 109 times

2

Is it possible to do this or do I really have to extract the file before to later read it?

In my code I’m doing so:

  string zipPath = @"C:\Users\Analistas\Desktop\ZipFile.zip";

        using (ZipArchive archive = ZipFile.OpenRead(zipPath))
        {
            var sample = archive.GetEntry("PdfFile.pdf");  
            string pdfContent = ReadPdfFile("PdfFile.pdf");
            if (sample != null)
            {
                using (var zipEntryStream = sample.Open())
                {
                    MessageBox.Show(pdfContent);
                }
            }
        }

And the method to read PDF:

        public string ReadPdfFile(string fileName)
        {
            StringBuilder text = new StringBuilder();

            if (File.Exists(fileName))
            {
                PdfReader pdfReader = new PdfReader(fileName);

                for (int page = 1; page <= pdfReader.NumberOfPages; page++)
                {
                    ITextExtractionStrategy strategy = new SimpleTextExtractionStrategy();
                    string currentText = PdfTextExtractor.GetTextFromPage(pdfReader, page, strategy);

                    currentText = Encoding.UTF8.GetString(ASCIIEncoding.Convert(Encoding.Default, Encoding.UTF8, Encoding.Default.GetBytes(currentText)));
                    text.Append(currentText);
                }
                pdfReader.Close();
            }
            return text.ToString();
        }

It’s not showing anything.

  • I believe that by fileName, would have to extract a stream and build a pdf clone from it.

1 answer

0


It is possible to read the pdf that is inside a zipped folder without having to extract it. Just instantiate the object PdfReader using the object Stream of the desired file.

var pdfReader = new PdfReader(ZipFileStream);

A suggestion would be to change your code to pass the object Stream for the method ReadPdfFile

var archive = ZipFile.OpenRead(zipPath);
var sample = archive.GetEntry("PdfFile.pdf");  
var zipEntryStream = sample.Open();

var pdfContent = ReadPdfFile(zipEntryStream);

And the method ReadPdfFile should be changed to read object Stream.

public string ReadPdfFile(Stream fileStream)
{
    ...
    PdfReader pdfReader = new PdfReader(fileStream);
    ...
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.