I've been able to write a code to create a new PDF or open an existing PDF and append. What I want to achieve now is to insert another PDF into it. Below is the sample code I've written so far to append PDF.
Document document = new Document(PageSize.A4);
PdfWriter writer = PdfWriter.getInstance(document, outputStream);
document.open();
PdfContentByte cb = writer.getDirectContent();
PdfReader reader = new PdfReader(templateInputStream);
PdfImportedPage page = writer.getImportedPage(reader, 1);
document.newPage();
cb.addTemplate(page, 0, 0);
// Append sample line
document.add(new Paragraph("my timestamp"));
document.close();
As per my knowledge Adobe reader does support inserting documents. Not sure if the same can be achieved using Java code too.
EDIT:
Below is the code I've written to embed PDF inside PDF. I'm getting error while I click and open embedded pdf/attachment.
public class AddEmbeddedFile {
public static final String SRC = "C:\\Users\\User\\Desktop\\testSource.pdf";
public static final String Embed = "C:\\Users\\User\\Desktop\\testEmbed.pdf";
public static final String DEST = "C:\\Users\\User\\Desktop\\testDest.pdf";
public static void main(String[] args) throws IOException, DocumentException {
File file = new File(DEST);
file.getParentFile().mkdirs();
new AddEmbeddedFile().manipulatePdf(SRC, DEST, Embed);
}
public void manipulatePdf(String src, String dest, String embed) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfReader reader2 = new PdfReader(embed);
int n = reader2.getNumberOfPages();
reader2.close();
ByteArrayOutputStream boas;
byte[] PDFContent = null;
byte[] PDFContent2 = new byte[0];
for (int i = 0; i < n; ) {
reader2.selectPages(String.valueOf(++i));
boas = new ByteArrayOutputStream();
PdfStamper stamper2 = new PdfStamper(reader2, boas);
PDFContent = boas.toByteArray();
byte[] c = new byte[PDFContent.length + PDFContent2.length];
System.arraycopy(PDFContent, 0, c, 0, PDFContent.length);
System.arraycopy(PDFContent2, 0, c, PDFContent.length, PDFContent2.length);
PDFContent2 = c;
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
PdfFileSpecification fs = PdfFileSpecification.fileEmbedded(
stamper.getWriter(), null, "tests.pdf", PDFContent2, "pdf", null, 0);
stamper.addFileAttachment("some test file", fs);
stamper.close();
}
}