AkinW AkinW - 4 months ago 22
Java Question

Double space not being preserved in PDF

I'm using the lowagie.text.pdf library to create a PDF document from within my java application, however I have realised that strings with double spacing in them i.e. "DOUBLE SPACE" aren't preserved.Is this a .PDF limitation or have I overlooked something else ?

Font font = FontFactory.getFont(FontFactory.HELVETICA, 8);
float[] columnWidths = new float[columnCount];

PdfPCell headerCell = new PdfPCell(new Phrase(gridColumn.getCaption(), font));

PdfPTable table = new PdfPTable(columnWidths);
table.getDefaultCell().setBorderWidth(0.5f);
table.getDefaultCell().setBorderColor(Color.LIGHT_GRAY);
table.setHeaderRows(1);

for (PdfPCell headerCell : headerCells) {
table.addCell(headerCell);
}

String value = "DOUBLE SPACED";

table.addCell(new Phrase(value, font));

Document pdfDocument = new Document(PageSize.A4.rotate(), 0, 0, 0, 0);
ByteArrayOutputStream pdfStream = new ByteArrayOutputStream();
PdfWriter.getInstance(pdfDocument, pdfStream);
pdfDocument.addTitle(caption);
pdfDocument.open();
pdfDocument.add(table);
pdfDocument.close();'


Thanks.

mkl mkl
Answer

I have realised that strings with double spacing in them i.e. "DOUBLE SPACE" aren't preserved

That depends on what you mean by being preserved.

I extended you sample a bit to print a single, a double, and a triple space

table.addCell(new Phrase("SINGLE SPACED", new Font(BaseFont.createFont(), 36)));
table.addCell(new Phrase("DOUBLE  SPACED", new Font(BaseFont.createFont(), 36)));
table.addCell(new Phrase("TRIPLE   SPACED", new Font(BaseFont.createFont(), 36)));

and furthermore updated the used classes to current iText 5.5.x variants.

If you look into the generated PDF internal instructions, you'll see

(SINGLE SPACED) Tj
...
(DOUBLE  SPACED) Tj
...
(TRIPLE   SPACED) Tj

Thus, iText does literally preserve the spaces.

The visual result:

Screenshot

As you see the gap is growing and growing. Thus, double and triple spaces are preserved in the visual representation of the PDF!


On the other hand, if you copy and paste using Adobe Reader, you get:

SINGLE SPACED
DOUBLE SPACED
TRIPLE SPACED

Thus, the current Adobe Reader does not copy&paste the space characters as they are inside the PDF but collapses multiple ones to a single one.

So:

Is this a .PDF limitation

This neither is a PDF limitation nor an iText limitation, it is a quirk of Adobe Reader (and some other PDF viewers, too).