简体   繁体   中英

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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM