使用 MemoryStream 将 pdf 保存在 Zip 中
本文关键字:存在 Zip 保存 pdf MemoryStream 使用 | 更新日期: 2024-11-08 15:31:28
我尝试以zip格式保存多个文件pdf,但我不能,有人可以帮助我吗?
using (MemoryStream memorystream = new MemoryStream())
{
string zip = @"C:'Temp'ZipFile.zip";
using (var archive = new ZipArchive(memorystream, ZipArchiveMode.Create, true))
{
for (int i = 0; i < 1; i++)
{
ZipArchiveEntry file = archive.CreateEntry(string.Format("Test{0}.pdf", i), CompressionLevel.Optimal);
using (Stream stream = file.Open())
{
Document document = new Document(PageSize.A4, 25, 25, 30, 30);
PdfWriter writer = PdfWriter.GetInstance(document, memorystream);
document.Open();
//
PdfPTable table = new PdfPTable(7);
Font fdefault = FontFactory.GetFont("Arial", 9, Font.NORMAL, BaseColor.DARK_GRAY);
table.AddCell(new Paragraph("Container", fdefault));
table.AddCell(new Paragraph("Code", fdefault));
table.AddCell(new Paragraph("ITEM", fdefault));
table.AddCell(new Paragraph("Reference", fdefault));
table.AddCell(new Paragraph("Description", fdefault));
table.AddCell(new Paragraph("Size", fdefault));
table.AddCell(new Paragraph("Quantity", fdefault));
document.Add(table);
document.Close();
writer.Close();
memorystream.Close();
}
}
}
using (var fileStream = new FileStream(zip, FileMode.Create))
{
memorystream.Seek(0, SeekOrigin.Begin);
memorystream.CopyTo(fileStream);
}
}
我用ExcelPackage这样做并工作,但这不起作用,我不知道问题所在。如果有人可以帮助我解决这个问题,我将不胜感激。
你有两个致命的缺陷。
首先,您将PdfWriter
绑定到 zip 的MemoryStream
,而不是从ZipArchiveEntry.Open()
中获取的Stream
。所以改变这一行:
PdfWriter writer = PdfWriter.GetInstance(document, memorystream);
对此:
PdfWriter writer = PdfWriter.GetInstance(document, stream);
第二个但与第一个相关,您将关闭 for 循环内部的 zip MemoryStream
。直接杀线:
memorystream.Close();
将所有这些放在一起并切换到首选的using
模式,您会得到:
using (var zipMemorystream = new MemoryStream())
{
using (var archive = new ZipArchive(zipMemorystream, ZipArchiveMode.Create, true))
{
for (int i = 0; i < 10; i++)
{
var file = archive.CreateEntry(string.Format("Test{0}.pdf", i), CompressionLevel.Optimal);
using (Stream stream = file.Open( ))
{
using( var document = new Document(PageSize.A4, 25, 25, 30, 30) )
{
using( var writer = PdfWriter.GetInstance(document, stream))
{
document.Open();
//
var table = new PdfPTable(7);
var fdefault = FontFactory.GetFont("Arial", 9, iTextSharp.text.Font.NORMAL, BaseColor.DARK_GRAY);
table.AddCell(new Paragraph("Container", fdefault));
table.AddCell(new Paragraph("Code", fdefault));
table.AddCell(new Paragraph("ITEM", fdefault));
table.AddCell(new Paragraph("Reference", fdefault));
table.AddCell(new Paragraph("Description", fdefault));
table.AddCell(new Paragraph("Size", fdefault));
table.AddCell(new Paragraph("Quantity", fdefault));
document.Add(table);
document.Close();
}
}
}
}
}
string zip = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "ZipFile.zip");
using (var fileStream = new FileStream(zip, FileMode.Create))
{
zipMemorystream.Seek(0, SeekOrigin.Begin);
zipMemorystream.CopyTo(fileStream);
}
}