我在网上查看了一些示例,并提出了使用iTextSharp合并pdfs的代码。但是我收到了一个错误:。
{“该文档没有网页。”}
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);
}
答案 0 :(得分:6)
GetImportedPage的页码是从1开始的。因此:
for (int X = 1; X < Pages + 1; X++)
{
Page = writer.GetImportedPage(reader, X);
writer.AddPage(Page);
}