0

I must insert a number at a fix position in an existing A4 pdf. I've tried the following as a first test, but that doesn't work(not text is added). What goes wrong? Here's my code:

byte[] omrMarks = omrFrame.getOmrImage();
Jpeg img = new Jpeg(omrMarks);
PdfImportedPage page = stamper.getImportedPage(source, pageNum);
PdfContentByte pageContent = stamper.getOverContent(pageNum);

pageContent.addImage(
  img, img.getWidth(), 0, 0, img.getHeight(), 15f, (page.getHeight() - 312));
pageContent.moveTo(10, 200);
pageContent.beginText();
pageContent.setLiteral("Test");
pageContent.endText();
Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165
Siegfried Storr
  • 67
  • 1
  • 1
  • 6

1 Answers1

3

There are many issues with this question.

This is certainly wrong:

pageContent.moveTo(10, 200);
pageContent.beginText();
pageContent.setLiteral("Test");
pageContent.endText();
  • The moveTo() method doesn't make sense; it has no effect on the text state object.
  • The text state object is illegal because there's no setFontAndSize() (it's very odd that this doesn't throw a RuntimeException, are you using an obsolete version of iText?)
  • The setLiteral() method should only be used to add some literal PDF syntax to a content stream.

For instance, something like:

pageContent.setLiteral("\n100 100 m\n100 200 l\nS\n");

should only be used if you understand that the following PDF syntax draws a line:

100 100 m
100 200 l
S

It's clear from your question that you don't understand PDF syntax, so you shouldn't use these methods. Instead you should use convenience methods such as the showTextAligned() method, which hide the complexity of PDF and save you a couple of lines.

Maybe you have a good reason to opt for the "hard way", but in that case, you should read the documentation, otherwise you'll continue using methods such as setLiteral() instead of showText(), moveTo() instead of moveText(), and so on, resulting in code you don't want your employer to see.

Furthermore, you're making the assumption that the lower left corner of the page has the coordinates (0,0). That's probably true for the majority of PDF documents found in the wild, but that's not true for all PDF documents. The MediaBox doesn't have to be [0 0 595 842], it could as well be [595 842 1190 1684]. Moreover: what if there's a CropBox? Maybe you're adding content that isn't visible because it's cropped away...

Bruno Lowagie
  • 75,994
  • 9
  • 109
  • 165