Nithin T K
Nithin T K

Reputation: 131

How fill form of an existing PDF and then add it to a new PDF using itext

I am using the following code

PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
AcroFields form = stamper.getAcroFields();
form.setField("name", "John");
stamper.setFormFlattening(true);
stamper.close();
reader.close();
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream(dest2));
document.open();
PdfContentByte cb = writer.getDirectContent();
//Loading the filled form again as a file
PdfReader reader2 = new PdfReader(dest);
PdfImportedPage page = writer.getImportedPage(reader2, 1);
document.newPage();
cb.addTemplate(page, 0, 0);
document.newPage();
document.add(new Paragraph("my timestamp"));
document.close();

Here i am loading the filled file again to add to the new pdf file, how to add the filled pdf to a new pdf from memory without loading as a file again.

Upvotes: 0

Views: 446

Answers (1)

mkl
mkl

Reputation: 95898

how to add the filled pdf to a new pdf from memory without loading as a file again.

In

PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));

replace the FileOutputStream by a ByteArrayOutputStream instance.

Then in

PdfReader reader2 = new PdfReader(dest);

use the PdfReader constructor accepting a byte array and feed it the byte array from the ByteArrayOutputStream instance.

Upvotes: 2

Related Questions