Chapter 6 of iText in action describes how to replicate a page using PdfSmartCopy / PdfCopy:
public void addDataSheets(PdfCopy copy) throws SQLException, IOException, DocumentException { // Create a database connection DatabaseConnection connection = new HsqldbConnection("filmfestival"); List<Movie> movies = PojoFactory.getMovies(connection); PdfReader reader; PdfStamper stamper; ByteArrayOutputStream baos; // Loop over all the movies and fill out the data sheet for (Movie movie : movies) { reader = new PdfReader(DATASHEET); baos = new ByteArrayOutputStream(); stamper = new PdfStamper(reader, baos); fill(stamper.getAcroFields(), movie); stamper.setFormFlattening(true); stamper.close(); reader = new PdfReader(baos.toByteArray()); copy.addPage(copy.getImportedPage(reader, 1)); } // Close the database connection connection.close(); }
This works great, but on my newly created document, the values inside the form fields are not visible unless I click on it. If I open the PDF in Chrome I can see the form values.
Apparently from Editable .pdf fields disappear (but visible on field focus) after save with evince, it comes out that there is a Flag which needs to be set on the pdf.
public void createPdf(String filename) throws IOException, DocumentException, SQLException { // step 1 Document document = new Document(); // step 2 PdfCopy copy = new PdfCopy(document, new FileOutputStream(filename)); // step 3 document.open(); // step 4 addDataSheets(copy); // step 5 document.close(); }
Is there a way to do it with the current API, without using reflection or re-openin the pdf?
Advertisement
Answer
Please take a look at the updated FillDataSheet example on the iText web site. You’ll discover that the following line was added:
fields.setGenerateAppearances(true);
iText used to ignore this flag and always created appearances, even if the PDF explicitly said that no appearances needed to be created. More recent versions take the value of the flag into account and don’t create appearances in case the PDF says that no appearances are needed (which is probably the case in your PDF).