I am working on an MVC project where I create dynamically pdf files(wkhtmltopdf) which I want to return in a zip file. The pdf files are generated on fly - I don't need to store them, so my code to return a single file is:
File(pdfBytes, "application/pdf", "file_name")
Taking a look on Microsoft docs their example goes through stored files:
string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
In my case I want to create N pdf files and return it to the view as a zip.. Something like:
ZipFile zip = new ZipFile();
foreach(var html in foundRawHTML)
{
//create pdf
//append pdf to zip
}
return zip;
Although this is not doable because:
Any help is welcome
Zipped (compressed) files take up less storage space and can be transferred to other computers more quickly than uncompressed files. In Windows, you work with zipped files and folders in the same way that you work with uncompressed files and folders.
Add Files or Folders to ZIP Archives Programmatically in C# April 22, 2020 · 5 min · Usman Aziz. The ZIP archives are used to compress and keep one or more files or folders into a single container. A ZIP archive encapsulates the files and folders as well as holds their metadata information.
You can use in memory byte arrays and ZipArchive from System.IO.Compression, there is no need to map the local drive:
public static byte[] GetZipArchive(List<InMemoryFile> files)
{
byte[] archiveFile;
using (var archiveStream = new MemoryStream())
{
using (var archive = new ZipArchive(archiveStream, ZipArchiveMode.Create, true))
{
foreach (var file in files)
{
var zipArchiveEntry = archive.CreateEntry(file.FileName, CompressionLevel.Fastest);
using (var zipStream = zipArchiveEntry.Open())
zipStream.Write(file.Content, 0, file.Content.Length);
}
}
archiveFile = archiveStream.ToArray();
}
return archiveFile;
}
public class InMemoryFile
{
public string FileName { get; set; }
public byte[] Content { get; set; }
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With