我正在为我的项目使用 iTextPDF + FreeMarker。基本上,我使用 FreeMarker 加载并填充 HTML 模板,然后使用 iTextPDF 将其渲染为 pdf XMLWorker
。
模板是:
<html>
<body style="font-family; ${fontName}">
<table>
<tr>
<td style="text-align: right">${timestampLabel} </td>
<td><b>${timestampValue}</b></td>
</tr>
<tr>
<td style="text-align: right">${errorIdLabel} </td>
<td><b>${errorIdValue}</b></td>
</tr>
<tr>
<td style="text-align: right">${systemIdLabel} </td>
<td><b>${systemIdValue}</b></td>
</tr>
<tr>
<td style="text-align: right">${descriptionLabel} </td>
<td><b>${descriptionValue}</b></td>
</tr>
</table>
</body>
</html>
这是我的代码:
SimpleDateFormat DATE_FORMAT = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
String errorId = "ERROR-01";
String systemId = "SYSTEM-01";
String description = "A SHORT DESCRIPTION OF THE ISSUE";
Map<String, String> parametersMap = new HashMap<String, String>();
parametersMap.put("fontName", fontName); //valid font name
parametersMap.put("timestampLabel", " TIMESTAMP:");
parametersMap.put("errorIdLabel", " ERROR ID:");
parametersMap.put("systemIdLabel", " SYSTEM ID:");
parametersMap.put("descriptionLabel", " DESCRIPTION:");
parametersMap.put("timestampValue", DATE_FORMAT.format(new Date()));
parametersMap.put("errorIdValue", errorId);
parametersMap.put("systemIdValue", systemId);
parametersMap.put("descriptionValue", description);
FreeMarkerRenderer renderer = new FreeMarkerRenderer(); //A utility class
renderer.loadTemplate(errorTemplateFile); //the file exists
String rendered = renderer.render(parametersMap);
File temp = File.createTempFile("document", ".pdf");
file = new FileOutputStream(temp);
Document document = new Document();
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
document.setPageSize(new Rectangle(290f, 150f));
/* * * * * * * * * * * * * * * * * * * * * * * * * * * * * */
document.setMargins(10, 10, 10, 10);
PdfWriter writer = PdfWriter.getInstance(document, file);
document.open();
InputStream is = new ByteArrayInputStream(rendered.getBytes());
XMLWorkerFontProvider provider = new XMLWorkerFontProvider();
provider.register(fontFile); //the file exists
FontFactory.setFontImp(provider);
byte[] errorStyle = getErrorStyleByteArray(); //returns a byte array from a css file (works)
XMLWorkerHelper helper = XMLWorkerHelper.getInstance();
helper.parseXHtml(writer, document, is, new ByteArrayInputStream(errorStyle), provider);
document.close();
file.close();
此代码工作正常,但固定高度是一个问题。
IE 假设:
errorId = "ERROR-01"
systemId = "SYSTEM-01"
description = "A SHORT DESCRIPTION OF THE ISSUE"
生成的文件是:
如果相反我使用
errorId = "ERROR-01"
systemId = "SYSTEM-01"
description = "A SHORT DESCRIPTION OF THE ISSUE. THIS IS MULTILINE AND IT SHOULD STAY ALL IN THE SAME PDF PAGE."
生成的文件是:
如您所见,在最后一个文档中,我有两页。我希望只有一页根据内容高度改变其高度。
使用 iText 可以实现这样的事情吗?