如何将现有磁盘上的PDF文件中的页面正确地添加到正在生成的内存中的PDF文档中?
我们使用iTextSharp编写了一个类来生成PDF文档,这个工作正常。目前,我们在最后一页作为图像添加了条款和条件:
this.nettPriceListDocument.NewPage();
this.currentPage++;
Image logo = Image.GetInstance("/inetpub/Applications/Trade/Reps/images/TermsAndConditions.gif");
logo.SetAbsolutePosition(0, 0);
logo.ScaleToFit(this.nettPriceListDocument.PageSize.Width, this.nettPriceListDocument.PageSize.Height);
this.nettPriceListDocument.Add(logo);
我有一个PDF文档中的图片,希望将其添加到其他需要生成的PDF文档中。如果我能够解决这个问题,就可以将其他需要的PDF文档附加到我正在生成的文档中。
我已经尝试过:
string tcfile = "/inetpub/Applications/Trade/Reps/images/TermsAndConditions.pdf";
PdfReader reader = new PdfReader(tcfile);
PdfWriter writer = PdfWriter.GetInstance(this.nettPriceListDocument, this.nettPriceListMemoryStream);
PdfContentByte content = writer.DirectContentUnder;
for (int pageno = 1; pageno < reader.NumberOfPages + 1; pageno++)
{
this.nettPriceListDocument.NewPage();
this.currentPage++;
PdfImportedPage newpage = writer.GetImportedPage(reader, pageno);
content.AddTemplate(newpage, 1f, 1f);
}
这会导致在
writer.DirectContentUnder
处出现“文档未打开”异常。我还尝试了以下方法:
string tcfile = "/inetpub/Applications/Trade/Reps/images/TermsAndConditions.pdf";
PdfReader reader = new PdfReader(tcfile);
PdfConcatenate concat = new PdfConcatenate(this.nettPriceListMemoryStream);
concat.AddPages(reader);
这会导致在文档通常的第一页上插入一个空白的、大小奇怪的页面。
我还尝试过:
string tcfile = "/inetpub/Applications/Trade/Reps/images/TermsAndConditions.pdf";
PdfReader reader = new PdfReader(tcfile);
PdfCopy copier = new PdfCopy(nettPriceListDocument, nettPriceListMemoryStream);
for (int pageno = 1; pageno < reader.NumberOfPages + 1; pageno++)
{
this.currentPage++;
PdfImportedPage newpage = copier.GetImportedPage(reader, pageno);
copier.AddPage(newpage);
}
copier.Close();
reader.Close();
这会导致在 copier.AddPage(newpage)
处出现 NullReferenceException 异常。
我也尝试过:
string tcfile = "/inetpub/Applications/Trade/Reps/images/TermsAndConditions.pdf";
PdfReader reader = new PdfReader(tcfile);
PdfCopyFields copier = new PdfCopyFields(nettPriceListMemoryStream);
copier.AddDocument(reader);
这也导致了在
copier.AddDocument(reader)
处出现了 NullReferenceException 异常。我从各种StackOverflow的问题和答案中得到了大多数的想法。但没有一个人处理过的一件事是,将现有PDF文件的新页面添加到尚未写入磁盘上PDF文件的内存中已经存在的文档中。该文档已经被打开并已经写入数据页面。如果我省略这个条款和条件程序,或者只将其编写为图像(如最初),则生成的PDF就可以正常输出。
最后:我该如何正确地将现有的磁盘上的PDF文件的页面添加到当前正在生成的内存PDF文档中?
非常感谢您对此的关注和支持。如果需要更多信息,请告知。
Document.Open()
因为文档已经打开并且已经添加了很多元素,该怎么办? - Troy