所以我有一個webapp,我目前正在研究。它運行在java/MVC模式/ MYsql/scala/play框架上。如何使用java MVC模式中的itext生成PDF文檔
我正在尋找一種方法來使用基於WEBAPP上的報告生成PDF文檔,所以基本上我們需要在報告頁面上添加一個「打印按鈕」,並將信息提取到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