我读到的关于此错误的所有内容都说该文件必须缺少"%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为null,从而导致返回secondPdf作为结果。我第二次经历,第一页作为firstPdf传入,新的第二页作为secondPdf传入。连接工作正常,结果实际上在上面链接的First.pdf文件中。
问题是当我去添加第三页时。我使用前一个传递(前两页)的输出作为第三遍的输入,以及一个新的PDF流。当我尝试使用PDF以前连接的页面初始化PdfReader时发生异常。
我觉得特别有趣的是它无法读取自己的输出。我觉得我必须做错事,但我既不知道如何避免这个问题,也不知道为什么标题有问题;它看起来很正常。如果有人能告诉我我的代码出错或者至少对PDF文件有什么不妥,我会非常感激。
答案 0 :(得分:3)
(评论回答)
我强烈建议不要将原始数据流传递给它们,而是通过调用.ToArray()
上的MemoryStream
来传递一个字节数组。 iTextSharp假设有一个专用的空流用于写入,因为它无法“就地”编辑现有文件。尽管流本质上映射到字节,但它们也具有固有属性,如Open
和Closed
以及Position
,这些属性可能会使事情变得混乱。