Reputation: 1
I am adding text to an existing pdf.
My code so far will add the text to the file but it deletes the original content that was on the pdf before, does anyone know how to fix this? So that the added text is on a new page and the original content of the pdf is on another page.
String field1 = ("/Users/Desktop/") + selectedFile.getName();
System.out.println(field1);
PdfDocument pdfDoc = new PdfDocument(new PdfWriter(field1));
PdfPage page = pdfDoc.addNewPage();
PdfCanvas pdfCanvas = new PdfCanvas(page);
Rectangle rectangle = new Rectangle(1,1, 600, 843);
pdfCanvas.rectangle(rectangle);
pdfCanvas.stroke();
Canvas canvas = new Canvas( pdfCanvas, pdfDoc, rectangle);
Scanner myObj = new Scanner(System.in); // Create a Scanner object
System.out.println("Enter text to add");
String addText = myObj.nextLine(); // Read user input
Paragraph p = new Paragraph(addText);
Scanner myObj1 = new Scanner(System.in); // Create a Scanner object
PdfFont font = PdfFontFactory.createFont(FontConstants.HELVETICA_BOLD);
p.setFont(font);
canvas.add(p);
pdfDoc.close();
canvas.close();
Upvotes: 0
Views: 455
Reputation: 7634
With PdfDocument pdfDoc = new PdfDocument(new PdfWriter(field1))
you will always create a new document with new content. You are now ignoring the original content. You must open the PDF in stamping mode.
Refer to the iText API: https://api.itextpdf.com/iText7/java/7.1.4/com/itextpdf/kernel/pdf/PdfDocument.html
Constructor and Description
PdfDocument(PdfReader reader)
Open PDF document in reading mode.
PdfDocument(PdfReader reader, DocumentProperties properties)
Open PDF document in reading mode.
PdfDocument(PdfReader reader, PdfWriter writer)
Opens PDF document in the stamping mode.
PdfDocument(PdfReader reader, PdfWriter writer, StampingProperties properties)
Open PDF document in stamping mode.
PdfDocument(PdfWriter writer)
Open PDF document in writing mode.
PdfDocument(PdfWriter writer, DocumentProperties properties)
Open PDF document in writing mode.
Upvotes: 2