我在网上查看了一些示例,并想出了这段代码来使用iTextSharp合并pdf。但我得到一个错误:。
{“文件没有页。”}
它在Page = writer.GetImportedPage(reader,X);处失败;
这是堆栈跟踪:
at iTextSharp.text.pdf.PdfPages.WritePageTree()
at iTextSharp.text.pdf.PdfWriter.Close()
at iTextSharp.text.pdf.PdfCopy.Close()
at iTextSharp.text.Document.Close()
调试时有3页。这是怎么了?
这是我的代码
public static MemoryStream MergePdfs(List<MemoryStream> pdfStreams)
{
//Create output stream
MemoryStream OutStream = new MemoryStream();
Document Document = null;
try
{
//Create Main reader
PdfReader Reader = new PdfReader(pdfStreams.ElementAt(0));
//Create Main Doc
Document = new Document(Reader.GetPageSizeWithRotation(1));
//Create main writer
PdfCopy Writer = new PdfCopy(Document, OutStream);
//Open document for writing
Document.Open();
//Add pages
AddPages(Reader.NumberOfPages, Reader, ref Writer);
//For each additional pdf after first combine them into main document
foreach (MemoryStream PdfStream in pdfStreams.Skip(1))
{
PdfReader Reader2 = new PdfReader(PdfStream);
// Add content
AddPages(Reader2.NumberOfPages, Reader2, ref Writer);
}
}
finally
{
// Step 5: Close the document
if (Document != null)
Document.Close();
foreach (var Strm in pdfStreams)
{
try { if (null != Strm) Strm.Dispose(); } catch { }
}
}
return OutStream;
}
private static void AddPages(int Pages, PdfReader reader, ref PdfCopy writer)
{
PdfImportedPage Page = null;
for (int X = 0; X < Pages; X++)
{
Page = writer.GetImportedPage(reader, X);
writer.AddPage(Page);
}
if (reader.AcroForm != null)
writer.CopyAcroForm(reader);
}
最佳答案
GetImportedPage的页码是从1开始的。从而:
for (int X = 1; X < Pages + 1; X++)
{
Page = writer.GetImportedPage(reader, X);
writer.AddPage(Page);
}