【发布时间】:2014-07-25 12:54:43
【问题描述】:
我所读到的有关此错误的所有内容都表明该文件必须在顶部缺少“%PDF-1.4”或类似内容;但是,我的文件包含它。我不是 PDF 格式方面的专家,但我确实仔细检查了我没有多个 %%EOF 或预告片标签,所以现在我不知道是什么导致我的 PDF 标题签名不好。如果您想查看该文件,请点击以下链接:Poorly formatted PDF
这就是我正在做的事情。我以 MemoryStream 的形式获取 PDF 的每一页,因此我必须将每一页附加到前几页的末尾。为了做到这一点,我正在使用 iTextSharp 的 PdfCopy 类。这是我正在使用的代码:
/// <summary>
/// Takes two PDF streams and appends the second onto the first.
/// </summary>
/// <param name="firstPdf">The PDF to which the other document will be appended.</param>
/// <param name="secondPdf">The PDF to append.</param>
/// <returns>A new stream with the second PDF appended to the first.</returns>
public Stream ConcatenatePdfs(Stream firstPdf, Stream secondPdf)
{
// If either PDF is null, then return the other one
if (firstPdf == null) return secondPdf;
if (secondPdf == null) return firstPdf;
var destStream = new MemoryStream();
// Set the PDF copier up.
using (var document = new Document())
{
using (var copy = new PdfCopy(document, destStream))
{
document.Open();
copy.CloseStream = false;
// Copy the first document
using (var reader = new PdfReader(firstPdf))
{
for (int i = 1; i <= reader.NumberOfPages; i++)
{
copy.AddPage(copy.GetImportedPage(reader, i));
}
}
// Copy the second document
using (var reader = new PdfReader(secondPdf))
{
for (int i = 1; i <= reader.NumberOfPages; i++)
{
copy.AddPage(copy.GetImportedPage(reader, i));
}
}
}
}
return destStream;
}
每次我收到一个新的 PDF 页面时,我都会将之前连接的页面 (firstPdf) 与新页面 (secondPdf) 一起传递给此函数。对于第一页,我没有任何先前连接的页面,因此 firstPdf 为空,从而导致 secondPdf 作为结果返回。我第二次通过时,第一页作为 firstPdf 传入,新的第二页作为 secondPdf 传入。串联工作得很好,结果实际上在上面链接的 First.pdf 文件中。
问题是当我去添加第三页时。我使用上一遍(前两页)的输出作为第三遍的输入,以及一个新的 PDF 流。当我尝试使用之前连接的 PDF 页面初始化 PdfReader 时发生异常。
我发现特别有趣的是它无法读取自己的输出。我觉得我一定做错了什么,但我既不知道如何避免问题,也不知道为什么标题有问题;它对我来说看起来很正常。如果有人能告诉我我的代码有什么问题,或者至少 PDF 文件有什么问题,我将不胜感激。
【问题讨论】:
-
我强烈建议不要传递原始流本身,而是通过在
MemoryStream上调用.ToArray()来传递字节数组。 iTextSharp 假设它有一个专用的空流用于写入,因为它无法“就地”编辑现有文件。尽管流本质上映射到字节,但它们也具有诸如Open和Closed和Position之类的固有属性,这些属性可能会使事情变得混乱。 -
我支持 Chris 的分析。您不关闭任何流的事实非常违反直觉。我不明白如何期望以这种方式创建有效的 PDF。
-
@ChrisHaas,您可以输入它作为对我帖子的回复,以便我可以将其标记为答案吗?昨天下午晚些时候,我终于得出了这个结论,并且取得了更大的成功。谢谢!
标签: c# pdf itextsharp .net-4.5