Question
How can I modify an existing PDF by adding new content using the iText library?
Document document = reader.read(input);
document.add(new Paragraph("my timestamp"));
writer.write(document, output);
Answer
iText is a powerful library that allows you to create and manipulate PDF documents in Java. To add content to an existing PDF, you need to follow a few steps, which involve reading the PDF, adding the content, and then writing it out.
import com.itextpdf.text.*;
import com.itextpdf.text.pdf.*;
public void addContentToExistingPDF(String src, String dest) throws Exception {
PdfReader reader = new PdfReader(src);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
PdfContentByte canvas = stamper.getOverContent(1);
BaseFont bf = BaseFont.createFont();
canvas.beginText();
canvas.setFontAndSize(bf, 12);
canvas.setTextMatrix(100, 700); // Set position
canvas.showText("Timestamp: " + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));
canvas.endText();
stamper.close();
reader.close();
}
Causes
- Misunderstanding the iText API's document manipulation process.
- Confusion about the roles of PdfReader and PdfWriter in the context of PDF modification.
Solutions
- Use `PdfReader` for reading existing PDF files.
- Utilize `PdfStamper` to modify existing content and add new elements.
- For writing out the modified document, ensure you use `PdfWriter` correctly.
Common Mistakes
Mistake: Not using PdfStamper for modifications.
Solution: Always use PdfStamper when you need to make changes to an existing PDF.
Mistake: Failing to close PdfReader and PdfStamper properly, leading to file locks or corrupt PDFs.
Solution: Ensure you always close both PdfReader and PdfStamper in a finally block or use try-with-resources.
Helpers
- iText add content to PDF
- modify existing PDF iText
- iText PDF manipulation
- Java iText tutorial
- add timestamp to PDF