Download Maven.
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.10</version>
</dependency
1. Write PDF using iTExtpublic class PdfWriteExample {
private static final String FILE_NAME = "/test/itext.pdf";
public static void main(String[] args) {
writeUsingIText();
}
private static void writeUsingIText() {
Document document = new Document();
try {
PdfWriter.getInstance(document, new FileOutputStream(new File(FILE_NAME)));
//open
document.open();
Paragraph p = new Paragraph();
p.add("This is my text 1");
p.setAlignment(Element.ALIGN_CENTER);
document.add(p);
Paragraph p2 = new Paragraph();
p2.add("This is my text 2"); //no alignment
document.add(p2);
Font f = new Font();
f.setStyle(Font.BOLD);
f.setSize(8);
document.add(new Paragraph("This is my text 3", f));
//close
document.close();
System.out.println("Done");
} catch (FileNotFoundException | DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2. Read PDF using iText
public class PdfReadExample {
private static final String FILE_NAME = "/test/itext.pdf";
public static void main(String[] args) {
PdfReader reader;
try {
reader = new PdfReader("f:/itext.pdf");
String textFromPage = PdfTextExtractor.getTextFromPage(reader, 1);
System.out.println(textFromPage);
reader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
Result:This is my text 1
This is my text 2
This is my text 3
Good luck!
0 comments:
Post a Comment