我在这里和“iText in Action”书中找到了许多解决方案,使用 PDFCopy 和 PDFSmartCopy 类来合并 PDF,但我见过的唯一一个类似的问题,那个人自己解决了,但没有不要发布答案。此帖Add an existing PDF from file to an unwritten document using iTextSharp问同样的问题,但在最后,所以他们建议关闭现有文档,然后使用 PDFCopy,在这里我想将其插入到任何地方。所以就这样吧。
我正在使用普通的部分、短语、文档和 PDFWriter 类创建一个包含文本和图像的 iTextSharp 文档。这是多年来编写的代码并且运行良好。现在,如果不可能的话,我们需要在创建此文档作为新的节或章节时插入现有的 PDF。我将 PDF 作为字节数组,因此获取 PDFReader 没有问题。但是,我无法弄清楚如何阅读该 PDF 并将其插入到我所在的现有文档中。如果需要,我可以访问 PDFWriter,但对于文档的其余部分,所有访问都是通过部分进行的。这是我所掌握的,如有必要,我可以添加 PDFWriter 作为另一个参数。
自最初的帖子以来,我已经取得了一些进展,并相应地修改了代码。
internal static void InsertPDF( Section section, Byte[] pdf )
{
this.document.NewPage();
PdfReader pdfreader = new PdfReader( pdf );
Int32 pages = pdfreader.NumberOfPages;
for ( Int32 page = 1; page <= pages; page++ )
{
PdfImportedPage page = this.writer.GetImportedPage( planreader, pagenum );
PdfContentByte pcb = this.writer.DirectContentUnder;
pcb.AddTemplate( page, 0, 0 );
this.document.NewPage();
}
}
它接近做我想做的事,但由于我显然不了解 iText 的完整工作原理,想知道这是否是正确的方法或者是否有更好的方法。
如果我可以提供任何其他信息,请告诉我。
如有任何指点,我们将不胜感激。
最佳答案
只是在答案中添加更多内容。通过研究哪些方法适用于 PdfTemplate(即 PdfImportedPage 的派生来源),最终找到了解决方案。我添加了一些内容来展示它如何与正在构建的文档的其余部分交互。我希望这对其他人有帮助。
internal static void InsertPDF( PdfWriter writer, Document document, Section section, Byte[] pdf )
{
Paragraph para = new Paragraph();
// Add note to show blank page is intentional
para.Add( new Phrase( "PDF follows on the next page.", <your font> ) );
section.Add( para );
// Need to update the document so we render this page.
document.Add( section );
PdfReader reader = new PdfReader( pdf );
PdfContentByte pcb = writer.DirectContentUnder;
Int32 pages = planreader.NumberOfPages;
for ( Int32 pagenum = 1; pagenum <= pages; pagenum++ )
{
document.NewPage();
PdfImportedPage page = writer.GetImportedPage( reader, pagenum );
// Render their page in our document.
pcb.AddTemplate( page, 0, 0 );
}
}
关于pdf - 在 iTextSharp 中,如何在创建新文档时包含现有 PDF,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22687285/