title: pdfbox: how to clone a page
body: <p>Using Apache PDFBox, I am editing an existing document and I would like to take one page from that document and simply clone it, copying whatever elements it contains. As an additional twist, I would like to get a reference to all the <code>PDField</code>s for any form fields in this newly cloned page. Here's the code I tried so far:</p>
  
  <pre><code>            PDPage newPage = new PDPage(lastPage.getCOSDictionary());
              PDFCloneUtility cloner = new PDFCloneUtility(pdfDoc);
              pdfDoc.addPage(newPage);
              cloner.cloneMerge(lastPage, newPage);
  
              // there doesn't seem to be an API to read the fields from the page, need to filter them out from the document.
              List&lt;PDField&gt; newFields = readPdfFields(pdfDoc);
              Iterator&lt;PDField&gt; i = newFields.iterator();
              while (i.hasNext()) {
                  if (i.next().getWidget().getPage() != newPage)
                      i.remove();
              }
  </code></pre>
  
  <p><code>readPdfFields</code> is a helper method I wrote to get all the fields in a document using the AcroForm.</p>
  
  <p>But this code seems to lead to some kind of crash/hang state in my JVM - I haven't been able to debug exactly what's happening but I'm guessing this is not actually the right way to clone a page. What is?</p>