简体   繁体   中英

Merging Documents iText7

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();

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM