【发布时间】:2018-10-14 16:12:45
【问题描述】:
是否可以使用 iTextSharp 将现有 PDF 文件附加到动态创建的 PDF 中?我已经尝试按照下面的代码使用 PdfCopy,但我收到了 Cannot access a closed Stream 错误。
我见过将实际 PDF 文件合并在一起的示例,但我没有存储完成的 PDF,只是将 MemoryStream 输出到 FilestreamResult:
private readonly float _spacingBefore = 3f;
private readonly float _spacingAfter = 3f;
private readonly float _totalWidth = PageSize.A4.Width - 80;
public MemoryStream CreateMemoryStream()
{
var document = new Document(PageSize.A4, 25, 25, 30, 30);
var workStream = new MemoryStream();
PdfWriter.GetInstance(document, workStream);
var pdfCopy = new PdfCopy(document, workStream);
document.Open();
var pdfPTable = new PdfPTable(1)
{
TotalWidth = _totalWidth,
LockedWidth = true,
SpacingBefore = _spacingBefore,
SpacingAfter = _spacingAfter
};
float[] widths = { 272f };
pdfPTable.SetWidths(widths);
var image = Image.GetInstance(HttpContext.Current.Server.MapPath("\\Images\\Logo.png"));
image.ScaleToFit(125f, 125f);
image.Alignment = Image.RIGHT_ALIGN;
var pdfPCell = new PdfPCell(image)
{
Border = 0,
HorizontalAlignment = Element.ALIGN_RIGHT
};
pdfPTable.AddCell(pdfPCell);
document.Add(pdfPTable);
pdfCopy.AddDocument(new PdfReader(HttpContext.Current.Server.MapPath("/Documents/Test.pdf")));
if (document != null)
{
document.Close();
}
var file = workStream.ToArray();
var memoryStream = new MemoryStream();
memoryStream.Write(file, 0, file.Length);
memoryStream.Position = 0;
return memoryStream;
}
public FileStreamResult Pdf(int id)
{
var memoryStream = CreateMemoryStream();
HttpContext.Response.AddHeader("content-disposition", "inline; filename=" + id + ".pdf");
return File(memoryStream, "application/pdf");
}
我也尝试了以下而不是pdfCopy.AddDocument(new PdfReader(HttpContext.Current.Server.MapPath("/Documents/Test.pdf")));
var pdfReader = new PdfReader(HttpContext.Current.Server.MapPath("/Documents/Test.pdf"));
var numberOfPages = pdfReader.NumberOfPages;
for (var i = 0; i < numberOfPages;)
{
pdfCopy.AddPage(pdfCopy.GetImportedPage(pdfReader, ++i));
}
无论采用哪种方法,我仍然会收到 Cannot access a closed Stream 错误。
任何帮助将不胜感激:-)
【问题讨论】:
-
我的 git github.com/fals/codingfirst/blob/master/random/… 中有这段代码用于合并文件。我还注意到您对 PdfWriter.GetInstance(document, workStream); 使用相同的流实例;
-
我正在尝试在内存中创建一个 PDF,一旦创建了初始文档,我希望将一个实际的 PDF 附加到动态创建的 PDF 的末尾,然后将连接的结果呈现给浏览器。
-
是的,我注意到,我 github 上的代码所做的与您的相同,在内存中,所有内容,我创建多个文档,然后附加然后插入循环,您也可以这样做。跨度>
-
谢谢,我查看了你的代码,好消息是错误已经消失,我得到了一个 PDF,但它只是附加的 PDF,而不是动态的 PDF,然后是附加的。我也尝试过使用
document.Add(pdfPTable); document.NewPage(); pdfCopy.AddDocument(new PdfReader(HttpContext.Current.Server.MapPath("/Documents/Test.pdf")));,但仍然没有乐趣。如果我注释掉pdfCopy.AddDocument(new PdfReader(HttpContext.Current.Server.MapPath("("/Documents/Test.pdf")));,我会收到错误The document has no pages。
标签: c# itext memorystream