使用飞碟在PDF中打印图像。
HTML代码:
<?xml version="1.0" encoding="utf-8" ?>
<html>
<p>
<img src="Smallcheck.jpg" width="20" height="21"/>
</p>
</html> 当我把HTML转换成PDF的时候,用飞梭。生成的PDF没有打印图像。
var outputForPdfStream = new this.ByteArrayOutputStream();
// tidy the html
var domdoc = this.domDocument;
var iTidy = new this.tidy();
iTidy.setShowWarnings(false);
iTidy.setXmlTags(false);
iTidy.setInputEncoding("UTF-8");
iTidy.setOutputEncoding("UTF-8");
iTidy.setXHTML(true);//
iTidy.setMakeClean(true);
domdoc = iTidy.parseDOM(inputStream, outputForPdfStream);
// Convert the document to XHTML panel and then rendering it into a PDF
var xhtmlPanel = new this.XHTMLPanel();
xhtmlPanel.setDocument(domdoc);
var renderer = new this.iTextRenderer();
renderer.setDocument(xhtmlPanel.getDocument(), null);
renderer.layout();
renderer.createPDF(bos);
bos.flush();
inputStream.close();
this.debug("INPUT STREAM" + inputStream);
var byteArray = bos.toByteArray();
var encodedString = this.StringUtil.base64Encode(byteArray);
this.debug("Encoded String" + encodedString);我是否需要使用任何特定的包打印图像PDF。如果你有任何问题请告诉我。
发布于 2020-03-07 15:25:45
为了将一幅图像嵌入到由Flying生成的PDF中,
1)将图像转换为base64编码的字符串。
Path path = Paths.get("src/main/resources/static/images/mastercard.png");
String base64Image = convertToBase64(path);函数将存储在如上文所示路径中的图像转换为base64编码的字符串。
private String convertToBase64(Path path) {
byte[] imageAsBytes = new byte[0];
try {
Resource resource = new UrlResource(path.toUri());
InputStream inputStream = resource.getInputStream();
imageAsBytes = IOUtils.toByteArray(inputStream);
} catch (IOException e) {
System.out.println("\n File read Exception");
}
return Base64.getEncoder().encodeToString(imageAsBytes);
}2)在胸腺网上下文中设置base64编码的图像
Context context = new Context();
String image = "data:image/png;base64, " + base64Image;
context.setVariable("image", image);
String html = templateEngine.process("template", context);3)在HTML中,设置图像的值如下所示:
<img th:src="${image}" style="width: 200px; height=100px"/>4)最后,将HTML模板呈现为PDF格式
ITextRenderer renderer = new ITextRenderer();
renderer.setDocumentFromString(html); // html -> String created in Step 2
renderer.layout();
final ByteArrayOutputStream baos = new ByteArrayOutputStream();
renderer.createPDF(baos)现在您有了生成的PDF的byteArrayOutputStream,您可以使用它选择将它们存储到文件服务器或以您选择的格式向客户端提供。
发布于 2016-03-03 16:02:45
您需要为您的图像设置上下文和相对路径,
renderer.setDocument(xhtmlPanel.getDocument(), null);如果改为,
renderer.setDocument(xhtmlPanel.getDocument(), "http:\\mywebsite:8080\images");并且您的图像应该位于上下文中指定的文件夹下,您可以在src中对图像使用相对路径,
<?xml version="1.0" encoding="utf-8" ?>
<html>
<p>
<img src="check/Smallcheck.jpg" width="20" height="21"/>
</p>
</html> https://stackoverflow.com/questions/35444130
复制相似问题