是否有任何方法可以使用spring batch ItemWriter将数据写入PDF文件。我看到了很多关于.txt,.xml等的例子。对于pdf writer我没有。 使用批量弹簧启动。 提前致谢。
答案 0 :(得分:1)
没有用于生成PDF文档的开箱即用ItemWriter
。但是,实现自己的应该可以直接使用各种开源库。
答案 1 :(得分:0)
您不需要ItemWriter即可将数据写入PDF。您可以做的是在写入器和读取器之间使用处理器。现有的API库可供您将DB,XML或JSON转换为PDF。这是来自Tutorials Point的示例,我在程序中成功读取了XML到DB,同时创建了PDF文件。
import java.io.File;
import java.io.IOException;
import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPage;
import org.apache.pdfbox.pdmodel.PDPageContentStream;
import org.apache.pdfbox.pdmodel.font.PDType1Font;
import org.springframework.batch.item.ItemProcessor;
public class CustomItemProcessor implements ItemProcessor<Tutorial, Tutorial> {
public static void drawTable(PDPage page, PDPageContentStream contentStream, float y, float margin,
String[][] content) throws IOException {
final int rows = content.length;
final int cols = content[0].length;
final float rowHeight = 50;
final float tableWidth = page.getMediaBox().getWidth() - (2 * margin);
final float tableHeight = rowHeight * rows;
final float colWidth = tableWidth / (float) cols;
final float cellMargin = 5f;
// draw the rows
float nexty = y;
for (int i = 0; i <= rows; i++) {
contentStream.drawLine(margin, nexty, margin + tableWidth, nexty);
nexty -= rowHeight;
}
// draw the columns
float nextx = margin;
for (int i = 0; i <= cols; i++) {
contentStream.drawLine(nextx, y, nextx, y - tableHeight);
nextx += colWidth;
}
// now add the text
contentStream.setFont(PDType1Font.HELVETICA_BOLD, 12);
float textx = margin + cellMargin;
float texty = y - 15;
for (int i = 0; i < content.length; i++) {
for (int j = 0; j < content[i].length; j++) {
String text = content[i][j];
contentStream.beginText();
contentStream.moveTextPositionByAmount(textx, texty);
contentStream.drawString(text);
contentStream.endText();
textx += colWidth;
}
texty -= rowHeight;
textx = margin + cellMargin;
}
}
@Override
public Tutorial process(Tutorial item) throws Exception {
System.out.println("Processing..." + item);
// Creating PDF document object
File f = new File("/Users/zhenxu/Desktop/test.pdf");
PDDocument doc = PDDocument.load(f);
// Creating a blank page
PDPage page = new PDPage();
doc.addPage(page);
PDPageContentStream contentStream = new PDPageContentStream(doc, page);
String[][] content = { { "Id", "" + item.getTutorial_id() }, { "Title", item.getTutorial_title() },
{ "Authour", item.getTutorial_author() }, { "Submission Date", item.getSubmission_date() } };
drawTable(page, contentStream, 700, 100, content);
contentStream.close();
doc.save("/Users/zhenxu/Desktop/test.pdf");
System.out.println("Hello");
return item;
}
这里,输入item
是输入XML。作业配置如下:
<!-- Defining a job-->
<batch:job id = "helloWorldJob">
<!-- Defining a Step -->
<batch:step id = "step1">
<batch:tasklet>
<!-- try use PDF converter -->
<batch:chunk reader="xmlItemReader" writer="mySqlItemWriter" processor="itemProcessor" commit-interval="10"></batch:chunk>
</batch:tasklet>
</batch:step>
</batch:job>
您还可以自定义您的读写器,以执行其他类型的工作。