0
votes

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();
1
Hint: Remove the lines one at a time and see which one is removing the original content. Is there any actually any content in the original PDF, what happens if you only open and save the pdf with no additions? What happens if you don't add a new page, or don't stroke the canvas? Try a bit of debugging like this and you be able to spot where your issue is. - sorifiend

1 Answers

2
votes

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.