如何使用java MVC模式中的itext生成PDF文档
所以我有一个webapp,我目前正在研究。它运行在java/MVC模式/ MYsql/scala/play框架上。如何使用java MVC模式中的itext生成PDF文档
我正在寻找一种方法来使用基于WEBAPP上的报告生成PDF文档,所以基本上我们需要在报告页面上添加一个“打印按钮”,并将信息提取到PDF。
谢谢
没有给你实际的代码,我要去给你,你如何能做到这一种方法。
如果我们假设你有某种形式的结构化数据,比如你想打印的项目列表,你可以使用一个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的解决方案,但我们的目标是向您展示的概念,而不是给你,你可以将代码复制/粘贴。
这个问题有很多可能的答案,但在这个答案中解释的概念当然是一个有效的答案。不是唯一一个(并且不是100%我会这样做),但值得一看。 – 2015-02-12 07:26:44
现在你让我着迷了!我很长一段时间没有使用过iText,但是我对图书馆的作者如何解决这个问题感兴趣:D – Lopina 2015-02-12 07:33:04
你的方法非常好,但是魔鬼在细节中。例如:我会使用一个'Chunk.NEWLINE'插入一个新行。至于架构,我会首先探讨以下哪个选项最适合:http://stackoverflow.com/questions/26218444/generate-and-design-pdf-with-itextsharp-or-similar(当然: @AAFF提出的问题太过宽泛,无法提供准确的建议)。您的建议与我的**选项1 **相似?-) – 2015-02-12 07:36:57
问题在哪里?试过了什么?你有什么问题? – 2015-02-12 07:20:07