Without giving you actual code, I'm going to give you one approach on how you can do it.
If we assume you have some sort of structured data, like a list of items you want to print, you can use a visitor pattern.
What you want it to do is have one visit(...)
method per type of item you want to print.
For example, if you had 2 classes:
public class Foo {
...
public int foo;
...
}
and
public class Bar {
...
public boolean bar;
...
}
then you could have your PDF visitor look something like this:
public class MyPDFVisitor {
...
public void visit(Foo foo) {
...
// do something with foo.foo
...
}
public void visit(Bar bar) {
...
// do something with Bar.bar
...
}
}
Now, I see you want to use iText
. So, what you could add to your MyPDFVisitor
class to support that is something like this:
public class MyPDFVisitor {
public MyPDFVisitor() {
this.document = new Document(PageSize.A4);
this.outputStream = new ByteArrayOutputStream();
try {
this.pdfWriter = PdfWriter.getInstance(this.document, this.outputStream);
} catch (DocumentException e) {
e.printStackTrace();
}
this.document.open();
}
private void addDocumentName(String description) throws DocumentException {
Paragraph preface = new Paragraph();
preface.setAlignment(ElementTags.ALIGN_CENTER);
addEmptyLine(preface, 1);
preface.add(new Paragraph(new Chunk(description, getTitleFont())));
addEmptyLine(preface, 2);
document.add(preface);
}
private void addEmptyLine(Paragraph paragraph, int number) {
for (int i = 0; i < number; i++) {
paragraph.add(new Paragraph(" "));
}
}
public void visit(Foo foo) {
Integer fooValue = foo.foo;
write(fooValue.toString(), Color.GREEN);
}
public void visit(Bar bar) {
Boolean barValue = bar.bar;
write(barValue.toString(), Color.RED);
}
public void write(String text, Color color) {
// do the actual write to document here
}
public InputStream getInputStream() {
try {
// you can do some final actions here, before closing the writing to the document
this.document.close();
} catch (DocumentException e) {
e.printStackTrace();
}
ByteArrayInputStream inputStream = new ByteArrayInputStream(outputStream.toByteArray());
return inputStream;
}
}
Please, don't confuse this for production code. I just gave you an example on how you can approach the problem and tackle it from there.
Disclaimer: Obviously, this is a Java solution, but the goal was to show you the concept, not give you the code you can copy/paste.