I have faced a task where I need to:
- read pdf template (no pictures, simple text with one table at the bottom for signature)
- recognize specific text
- replace specific text with data from system
- generate new pdf with replaced text to user
At first I have tried Lowagie library which from 2... version moved to itext Then used Itext Then moved to PDFBox
I saw many examples in stackoverflow and such where point source pdf, destination pdf, word to change Copy it, paste it, make classes imports but the new pdf is generated without any changes
Am trying on these libs:
// PDFBox generator
compile 'org.apache.pdfbox:pdfbox:2.0.9'
// Itext generator
compile 'com.itextpdf:itext-pdfa:5.5.10'
compile 'com.itextpdf:itextg:5.5.9'
// Lowagie generator
compile group: 'com.lowagie', name: 'itext', version: '2.1.7'
Maybe libs are changing and this causes some functions not to work, but can you suggest a working solution for you?
Have tried these covnertions:
private void processPDF(String src, String dest) throws IOException, DocumentException {
PdfReader reader = new PdfReader(src);
PdfDictionary dict = reader.getPageN(1);
PdfObject object = dict.getDirectObject(PdfName.CONTENTS);
if(object instanceof PRStream){
PRStream stream = (PRStream)object;
byte[] data = PdfReader.getStreamBytes(stream);
String dd = new String(data, "UTF8")
.replace("text", "replacedText");
stream.setData(dd.getBytes("UTF8"));
}
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(dest));
stamper.close();
reader.close();
}
private void processPDF3(String src, String dest) throws InvalidPasswordException, IOException {
Map<String, String> map = new HashMap<>();
map.put("text", "replacedText");
File template = new File(src);
PDDocument document = PDDocument.load(template);
List<PDField> fields = document.getDocumentCatalog().getAcroForm().getFields();
for (PDField field : fields) {
for (Map.Entry<String, String> entry : map.entrySet()) {
if (entry.getKey().equals(field.getFullyQualifiedName())) {
field.setValue(entry.getValue());
field.setReadOnly(true);
}
}
}
File out = new File(dest);
document.save(out);
document.close();
}
Also used this: iText Add values to placeholders in PDF cover page dynamically
And variations of this: PDFBox 2.0 RC3 -- Find and replace text
Would be very thanksful for your help