I'm using com.itextpdf
library in java
to generate and edit the PDF.
I'm facing a wired issue: where the PDF contents (date) is not rendered/displayed properly inside the PDF.
I'm initially created a PDF file uisng itext only and later in the post processing - replacing the PDF contents (date).
For example: Date 28 Nov 2020 is rendered like below (Slight rendering changes on each run - on common or space or number level):
Things I tried:
- Upgraded the itext from older version:
5.5.6
and latest:5.5.13.2
. - Tried Multiple fonts.
- Encoding styles: both:
UTF-8
andISO-8859-1
, still no luck.
Any pointer would be helpful.
//initial placeholder:
String TEMPORARY_DATE_PLACE_HOLDER = "----------------";
//BaseFont (tried with both embedded as true / false):
BaseFont.createFont("/arial.ttf", BaseFont.WINANSI, false);
-
-
-
// post processing: where the placeholder is replaced.
reader = new PdfReader(InputPDF);
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 CHARACTER_ENCODING_SET = "ISO-8859-1";
String dataString = new String(data, CHARACTER_ENCODING_SET);
if ( dateFormatList.contains(requiredDate)) {
dataString = dataString.replaceAll(TEMPORARY_DATE_PLACE_HOLDER, new SimpleDateFormat(dateFormat).format(requiredDate));
}
stream.setData(dataString.getBytes(CHARACTER_ENCODING_SET));
}
stamper = new PdfStamper(reader, out);
stamper.close();
reader.close();
byte[] fileContent = out.toByteArray();
helperToWrite(new ByteArrayInputStream(fileContent), "OutputPDF");
//Helper method to write into File:
private File helperToWrite(nputStream inputStream, String name){
try (OutputStream outputStream = new FileOutputStream(file)) {
int read = 0;
byte[] bytes = new byte[1024];
while ((read = inputStream.read(bytes)) != -1) {
outputStream.write(bytes, 0, read);
}
} catch (Exception e) {
}
return file;
}