Anyway to extract and replace editable text in a PDF file in java.
Also anyway to find/identify any specific image and replace it?
Thanks alot.
public static void main(String[] args) throws Exception {
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile("input/input.pdf");
//Extract text
ExtractText(pdf);
//Replace text
ReplaceText(pdf);
//save to file
pdf.saveToFile("output/Result.pdf");
pdf.close();
}
private static void ExtractText(PdfDocument pdf) throws Exception{
StringBuilder builder=new StringBuilder();
for (PdfPageBase page : (Iterable<PdfPageBase>) pdf.getPages()) {
builder.append(page.extractText(true));
}
//write to txt
FileWriter writer;
writer = new FileWriter("output/ExtractText.txt");
writer.write(builder.toString());
writer.flush();
}
private static void ReplaceText(PdfDocument pdf) throws Exception {
PdfTextFind[] result = null;
for (PdfPageBase page : (Iterable<PdfPageBase>) pdf.getPages()) {
result = page.findText("OldText").getFinds();
for (PdfTextFind find : result) {
//cover the old text with new text
find.applyRecoverString("NewText", Color.white, true);
}
}
}
//Load the PDF file
PdfDocument pdf = new PdfDocument();
pdf.loadFromFile("input/input.pdf");
//Get the first page
PdfPageBase page = pdf.getPages().get(0);
//Load an image
PdfImage image = PdfImage.fromFile("input/sample.jpg");
//Replace the first image in the first page with the loaded image
page.replaceImage(0, image);
//Save the file
pdf.saveToFile("output/ReplaceImage.pdf");
Point2D pStart=new Point2D.Float(123.12f,12.33f);
Point2D pEnd=new Point2D.Float(100.12f,23.63f);
page.getCanvas().drawLine(pen, pStart, pEnd);float startAngle = 0;
float sweepAngle = 110;
Rectangle2D.Float rect3= new Rectangle2D.Float(0, 110, 50, 50);
page.getCanvas().drawArc(pen, rect3, startAngle, sweepAngle);String result="E:\\filePath\\filename.pdf";
doc.saveToFile(result, FileFormat.PDF);