5

I am trying to copy one page from an existing .pdf file and paste it to a new document like this:

     using (var writer = new PdfWriter(OutputFile))
        {
          var reader = new PdfReader("Templates//PDF_Template_Empty.pdf");
          PdfDocument template = new PdfDocument(reader);
          var titlepage = template.GetPage(1);
          using (var pdf = new PdfDocument(writer))
            {
                pdf.AddPage(titlepage); // exception

But on .AddPage() it throws this exception :

iText.Kernel.PdfException: 'Page iText.Kernel.Pdf.PdfPage cannot be added to document iText.Kernel.Pdf.PdfDocument, because it belongs to document iText.Kernel.Pdf.PdfDocument.'

How can I fix this ?

mkl
  • 90,588
  • 15
  • 125
  • 265
Сергей
  • 780
  • 4
  • 13
  • 31
  • What `PdfWriter` are you using? Can you provide a link to its documentation, for instance, or provide the name of its assembly or full namespace? – Shaun Luttin Apr 12 '18 at 15:46

1 Answers1

8

A PDF page object usually has a number of related objects. If you only add the page itself to a new document and not the related objects, the resulting page would be incomplete.

Thus, iText 7 checks in AddPage whether the page in question has been created inside the target document or not, and in the latter case throws an exception to prevent missing dependent objects.

To copy pages across documents there is the PdfDocument method CopyPagesTo with many overloads. For you e.g.

PdfDocument template = new PdfDocument(reader);
using (var pdf = new PdfDocument(writer))
{
    // copy template pages 1..1 to pdf as target page 1 onwards
    template.CopyPagesTo(1, 1, pdf, 1); 
}

(Beware, if there are extras on the page, you might want to choose an overload of that method which accepts an additional IPdfPageExtraCopier instance, e.g. for AcroForm fields a PdfPageFormCopier.)

mkl
  • 90,588
  • 15
  • 125
  • 265
  • do you mean, that I can change fields in new page, which was copied from `template` document ? – Сергей Apr 13 '18 at 07:43
  • 1
    More exactly: Only if you copy the page with a `PdfPageFormCopier`, the AcroField fields will be copied to the target document. In that case I would expect you will be able to change their values in the target document (I have not tried that yet). – mkl Apr 13 '18 at 07:59