1

I have PDF generation feature in my app. I am using iTextPDF for generating reports, so it works well. The problem is not exactly in pdf generation but in approach. Currently PDF generation code looks horrible, hard-coded and not flexible, so there is a lot of duplication and everything is highly coupled.

Are there any best or common practices for such a task? Maybe some architectural approach or pattern? I would be very grateful for any advice and code example that was proven as reliable and flexible.

  • Be aware of iTextPDF license the 5.x are not free if it's for commercial usage. – Walfrat Apr 21 '16 at 11:45
  • @Walfrat: AFAIK, iTextPDF is dual licensed, and APGL will forbid commercial distribution (not usage) without opening the source code of the derived works. – Doc Brown Apr 21 '16 at 13:56
7

As long as you want only a PDF version of your report, it's enough to simply apply good factoring practices. Write utility functions, extract common code into subroutines, choose good method names, and after a while you'll have a pretty decent maintainable report generator.

However, the second it looks as if you'll have to support any other output format than PDF for the same report (e.g. text, HTML email, whatever), immediately refactor your code into a generator (decides what information to print and in what order) and a renderer (knows how to produce bold, centered, or double-spaced output).

Then, whenever the report content changes, you only have to update the generator, and whenever the style requirements change, you only have to update a small part of your renderers. And when yet another output format is required, you only have to add another renderer subclass rather then walk through your entire codebase yet again.

  • You advice about supporting and abstracting from output document is great.I know about this, but haven't thought in this case about such possible way to bring some abstraction into my code. I totally agree with you all your ideas. Thanks again – CROSP Apr 21 '16 at 17:58
  • Pick a "single source" and then export from that to your desired targets. Back in the day, that would've been a simple XML format. Nowadays docx is often a good choice for that single source (especially if it is one of the ultimate targets of course), since there are many libraries for creating it, and for converting to text, HTML, PDF etc. – JasonPlutext Jun 19 '18 at 0:58

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.