[英]Attempting to merge PDFs using iTextSharp v4 throws an exception
I have tried a couple of different code samples and they all throw the same exception:我尝试了几个不同的代码示例,它们都抛出了相同的异常:
System.InvalidCastException was unhandled by user code
Message=Unable to cast object of type 'iTextSharp.text.pdf.PdfArray' to type 'iTextSharp.text.pdf.PRIndirectReference'.
Source=itextsharp
StackTrace:
at iTextSharp.text.pdf.PdfCopy.CopyObject(PdfObject inp)
at iTextSharp.text.pdf.PdfCopy.CopyDictionary(PdfDictionary inp)
at iTextSharp.text.pdf.PdfCopy.AddPage(PdfImportedPage iPage)
This example uses PdfCopy.此示例使用 PdfCopy。 I have also tried it with PdfWriter:
我也用 PdfWriter 尝试过:
public MemoryStream Merge(MemoryStream outputStream,List<PdfReader> documents)
{
if (outputStream == null || !outputStream.CanWrite)
throw new Exception("OutputStream is null or you can't write to it.");
Document newDocument = null;
try
{
newDocument = new Document(documents[0].GetPageSizeWithRotation(1));
PdfCopy pdfWriter = new PdfCopy(newDocument, outputStream);
newDocument.Open();
//PdfContentByte pdfContentByte = pdfWriter.DirectContent;
foreach (PdfReader pdfReader in documents)
{
for (int page = 1; page <= pdfReader.NumberOfPages; page++)
{
//newDocument.NewPage();
PdfImportedPage importedPage = pdfWriter.GetImportedPage(pdfReader, page);
pdfWriter.AddPage(importedPage);
}
}
}
finally
{
outputStream.Flush();
if (newDocument != null)
newDocument.Close();
outputStream.Close();
}
return outputStream;
}
With this code, the exception happens at AddPage.使用此代码,异常发生在 AddPage。 On a PdfWriter, it happens at document close.
在 PdfWriter 上,它发生在文档关闭时。 I really don't know the iTextSharp internals all that well...
我真的不太了解 iTextSharp 内部结构......
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.