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

时间:2014-03-27 12:12:54

标签: pdf pdf-generation itextsharp

我在这里和“动作中的iText”中找到了很多解决方案。预订,使用PDFCopy和PDFSmartCopy课程合并PDF,但我见过唯一类似的问题,这个人自己解决了这个问题,但没有发布答案。这篇文章Add an existing PDF from file to an unwritten document using iTextSharp提出了同样的问题,但最后提问,所以他们建议关闭现有文档,然后使用PDFCopy,在这里我想把它插入任何地方。所以这里。

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

如果我能提供任何其他信息,请与我联系。

任何指针都会受到赞赏。

2 个答案:

答案 0 :(得分: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 );
     }
}

答案 1 :(得分:0)

要将现有的pdf插入新页面,我已更改订单新页面

PdfImportedPage page2 = writer.GetImportedPage(pdf, 1);
                cb.AddTemplate(page2, 0, 0);
                document.NewPage();