pbforster
pbforster

Reputation: 381

Creating unit tests for generated PDFs using iText

We're using iText to read an input PDF, then add messaging and saving the output.

PdfReader reader = new PdfReader(inputFilepath);
PdfStamper stamper = new PdfStamper(reader, new FileOutputStream(outputFilename, true));
PdfContentByte over = stamper.getOverContent(1);
over.beginText();
over.showTextAligned(align, text, x, y, angle);
...
over.endText();
stamper.close();

Is there a way of reading in a PDF generated in a unit test and then checking that the supplied text exists at the correct x, y coordinates?

Upvotes: 6

Views: 5407

Answers (2)

Fernando Cuenca
Fernando Cuenca

Reputation: 151

Generally speaking, don't test the platform (or, in this case, third party libraries you're using.) Instead, test that you're interacting with it correctly.

In this case, this would imply assuming that showTextAligned() will do the right thing, provided that the correct coordinates are passed in. I would then focus on testing that.

This will probably mean that I'd need to hide all the interactions with the PDF classes behind an interface, and that I'd pass a mock of that interface to the calculating code, using it to verify that the correct values were passed for the given sample input.

Upvotes: 2

Kartick Vaddadi
Kartick Vaddadi

Reputation: 4998

As a shortcut, you can test the order of text in the PDF in a particular page, using PdfReader.getPageContent(int pageNumber).

This not ideal, but it can be a poor man's positioning test, assuming you print text left to right and top to bottom.

Upvotes: -1

Related Questions