dependencies {
// org.apache.pdfbox
implementation 'org.apache.pdfbox:pdfbox:2.0.29'
}
여기서 핵심이 되는 부분은 PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true);
여기이며, 특히나 PDPageContentStream.AppendMode.APPEND
이 부분 이다. 해당 값이 없으면 그냥 overwrite 해서 덮어씌어버린다.
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import java.io.File;
import java.io.IOException;
public class AddingTextToPdf {
public static void main(String[] args) throws IOException {
//Loading an existing document
PDDocument doc = PDDocument.load(new File("C:\\workspace\\private\\my-practice\\src\\main\\resources\\test.pdf"));
//Creating a PDF Document
PDPage page = doc.getPage(0);
PDPageContentStream contentStream = new PDPageContentStream(doc, page, PDPageContentStream.AppendMode.APPEND, true);
//Begin the Content stream
contentStream.beginText();
//Setting the font to the Content stream
contentStream.setFont(PDType1Font.TIMES_ROMAN, 16);
//Setting the position for the line
contentStream.newLineAtOffset(100, 480);
String text = "This is an example of adding text to a page in the pdf document. " +
"we can add as many lines as we want like this using the draw string method" +
"of the ContentStream class";
//Adding text in the form of string
contentStream.showText(text);
//Ending the content stream
contentStream.endText();
System.out.println("Content added");
//Closing the content stream
contentStream.close();
//Saving the document
doc.save(new File("C:\\workspace\\private\\my-practice\\src\\main\\resources\\AddText_OP.pdf"));
//Closing the document
doc.close();
}
}
구글에 pdf에 텍스트 추가
같은 걸로 검색하면 이런 내용들이 나온다.
근데 실제로 해당 내용을 따라해보면 pdf 기존 내용 위에 내가 원하던 텍스트를 추가하는게 아니라 아예 기존 내용을 다 날리고 그 위에 텍스트를 추가한다.
즉 add 가 맞기는 한데 기존 내용을 날리고 새롭게 추가하니까 그냥 빈 pdf에 text를 추가하는게 맞다.
나는 기존의 내용을 살려두고 그 위에 내가 원하는 텍스트를 쓰는 형태를 원했는데 (테이블이 있으면 빈 테이블에 내가 원하는 텍스트를 넣는 것)
검색을 하니까 대부분 이런 내용들만 나오고, 해당 라이브러리도 overwrite라고 적혀있어서 한참 헤맸다.
(※overwriter 니까 기존 내용을 날리고 새로운 내용을 쓰는게 맞지 않냐 라고 생각하신다면 제대로 생각하신게 맞습니다. 저는 지금까지 의미를 조금 다르게 이해하고 있었던 것 같습니다.😅😅)
겨우 ChatGPT를 통해서 문제를 알게되었고, 제가 원하는 결과를 얻을 수 있었습니다.
나는 지금까지 기존 파일 위에 새로운 내용을 추가하는 걸 덮어쓰기 라고 생각을 했었던 것 같다. 그래서 overwrite를 보고는 당연히 기존 내용 위에 새로운 내용을 추가한다고 생각했었어서 한참 헤맸다. [당연히 기존의 내용을 지운다고 생각을 했으면 좀 덜 헤맸을텐데 ...]
ChatGPT에 의하면 기존의 내용을 다 날리고 새로운 내용으로 덮는게 Overwrite [덮어쓰기] 라고 한다.