我正在尝试从包含 html 代码的 Java 字符串生成 pdf 文档。我使用“Freemarker”作为模板引擎来生成 html 内容,然后使用“Flying-Saucer”将生成的 html 转换为 pdf。我的问题是生成的 pdf 中没有呈现图像。关于我如何生成的确切细节如下:
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.List;
import org.xhtmlrenderer.pdf.ITextRenderer;
import com.google.inject.Inject;
import com.google.inject.Singleton;
import com.lowagie.text.DocumentException;
import freemarker.template.Configuration;
import freemarker.template.DefaultObjectWrapper;
import freemarker.template.SimpleHash;
import freemarker.template.SimpleSequence;
import freemarker.template.Template;
import freemarker.template.TemplateException;
@Singleton
public class FlyingSaucerTaxInvoicePdfPrinter implements ITaxInvoicePdfPrinter {
private final Configuration m_cfg;
@Inject
public FlyingSaucerTaxInvoicePdfPrinter() {
// TODO: Following should be singletons and injected
m_cfg = new Configuration();
m_cfg.setObjectWrapper(new DefaultObjectWrapper());
m_cfg.setClassForTemplateLoading(this.getClass(), "/");
}
private Template getTemplate() throws IOException {
return m_cfg.getTemplate(PdfResources.TAX_INVOICE_TEMPLATE);
}
@Override
public void printToPdf(TaxInvoiceUiPb taxInvoice, OutputStream pdfOutputStream) {
OutputStream htmlOuputStream = null;
try {
htmlOuputStream = new ByteArrayOutputStream();
printHtml(htmlOuputStream, taxInvoice);
generatePDF(htmlOuputStream, pdfOutputStream);
} catch (Exception e) {
throw new LoggedRuntimeException(e);
} finally {
try {
htmlOuputStream.close();
} catch (IOException e) {
throw new LoggedRuntimeException(e);
}
}
}
private void generatePDF(OutputStream htmlOuputStream, OutputStream pdfOutputStream)
throws DocumentException, IOException {
try {
ITextRenderer renderer = new ITextRenderer(30.666f, 20);
String html = htmlOuputStream.toString();
logHtml(html);
renderer.setDocumentFromString(html);
renderer.layout();
renderer.createPDF(pdfOutputStream);
} finally {
pdfOutputStream.close();
}
}
// Some methods not shown as irrelevant
}
生成的 html(仅显示相关部分)是:
<body>
<div class="main" background="images/invoice-bg.jpg">
<img src="images/invoice-bg.jpg"></img>
<div class="header">
<div class="logo"><img src="images/invoice-logo.jpg" alt="" border="0" /></div>
<div class="heading">booking invoice</div>
</div>
<div class="clear"></div>
</div>
</body>
此代码作为部署在 Tomcat 上的 War 运行。作为 tree 命令的输出(在 WEB-INF 中运行),War 中图像的位置是:
|-- classes
| |-- com
| | `-- ilodge
| | `-- pmsServerWar
| | |-- PmsServerWarListener.class
| | `-- PmsServerWarServletModule.class
| |-- images
| | |-- invoice-bg.jpg
| | |-- rupees-icon-total.png
| | |-- thank-you.jpg
| | |-- total-bold-rupee.png
| | `-- ul-bor.jpg
| |-- taxInvoice.css
| |-- taxInvoiceFooter.ftl
| |-- taxInvoice.ftl
| `-- test.ftl
|-- lib
| |-- addressServer-1.0-SNAPSHOT.jar
| |-- addressUiProtobuf-1.0-SNAPSHOT.jar
| `-- xml-apis-1.3.03.jar
`-- web.xml
为简洁起见,我截断了输出。请帮忙。
谢谢和问候, 罗希特