首页 文章

在iTextSharp中,如何在创建新文档时包含现有PDF

提问于
浏览
2

我使用PDFCopy和PDFSmartCopy类进行了操作' book, to merge PDF',但唯一类似的问题是我发布了答案 . 这篇文章Add an existing PDF from file to an unwritten document using iTextSharp问同样的问题,但最后问题,所以他们建议关闭现有文档,然后使用PDFCopy,在这里我想把它插入任何地方 . 所以这里 .

我正在使用普通的Sections,Phrases,Document和PDFWriter类创建一个包含文本和图像的iTextSharp文档 . 这是多年来编写的代码,工作正常 . 现在我们需要在创建此文档时插入现有PDF作为新的Section或章节,如果不可能的话 . 我将PDF作为Byte数组,因此获取PDFReader没有问题 . 但是,我无法弄清楚如何阅读PDF并将其插入到现有文档中 . 如果需要,我可以访问PDFWriter,但对于文档的其余部分,所有访问都是通过Sections进行的 . 这是我所拥有的,如果有必要,我可以将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的全部工作,不知道这是正确的方式还是有更好的方法 .

如果我能提供任何其他信息,请告诉我 .

任何指针将不胜感激 .

1 回答

  • 4

    只需在答案中添加一点肉 . 最终通过研究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 );
         }
    }
    

相关问题