在不提供实际代码的情况下,我将提供一种方法来说明如何做到这一点。
如果我们假设您有某种结构化数据,例如要打印的项目列表,您可以使用visitor 模式。
您希望它为每种要打印的项目类型提供一个visit(...) 方法。
例如,如果你有 2 个类:
public class Foo {
...
public int foo;
...
}
和
public class Bar {
...
public boolean bar;
...
}
那么你可以让你的 PDF 访问者看起来像这样:
public class MyPDFVisitor {
...
public void visit(Foo foo) {
...
// do something with foo.foo
...
}
public void visit(Bar bar) {
...
// do something with Bar.bar
...
}
}
现在,我看到你想使用iText。所以,你可以添加到你的 MyPDFVisitor 类来支持它是这样的:
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;
}
}
请不要将其与生产代码混淆。我只是举了一个例子,说明如何解决问题并从那里解决。
免责声明:显然,这是一个 Java 解决方案,但目的是向您展示概念,而不是为您提供可以复制/粘贴的代码。