我正在使用Flying Saucer API
和iText PDF
将HTML内容转换为PDF。
这需要以下库:
由于该库不支持input type checkbox
所以我使用checkbox image
以PDF格式呈现。
但是,图像不会出现。它没有任何表现。
例:
StringBuilder myHtml = new StringBuilder();
myHtml.append("<html><img src=\"images/invoice-bg.jpg\"></img></html>");
// if you have html source in hand, use it to generate document object
Document document = XMLResource.load( new ByteArrayInputStream(
myHtml.toString().getBytes() ) ).getDocument();
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument( document, null );
renderer.layout();
String fileNameWithPath = "D:/Temp/PDF-XhtmlRendered.pdf";
FileOutputStream fos = new FileOutputStream( fileNameWithPath );
renderer.createPDF( fos );
fos.close();
System.out.println( "File 1: '" + fileNameWithPath + "' created." );
您应该使用最新版本的Flying-Saucer(目前为9.1.9)。你可以在mvnrepository找到。
您还应该检查文件images/invoice-bg.jpg
是否存在,并且可以从项目的根目录访问。
如果您的路径正确,生成的PDF将包含您的图像。
如果您使用具有相对文件路径的资源,则需要在setDocument
调用中指定基本URL。
给出图像的完整路径然后它工作。
我通过直接点击以下网址检查了这个:
http://localhost:8001/userApi/resources/images/invoice-bg.jpg
如果遇到类似问题,这可能有助于某人
StringBuilder myHtml = new StringBuilder();
myHtml.append("<html><img
src=\""+serverName+"/userApi/resources/images/invoice-bg.jpg\"
style=\"margin-top:-4px;\" ></img></html>");
// if you have html source in hand, use it to generate document object
Document document = XMLResource.load( new ByteArrayInputStream(
myHtml.toString().getBytes() ) ).getDocument();
ITextRenderer renderer = new ITextRenderer();
renderer.setDocument( document, null );
renderer.layout();
String fileNameWithPath = "D:/Temp/PDF-XhtmlRendered.pdf";
FileOutputStream fos = new FileOutputStream( fileNameWithPath );
renderer.createPDF( fos );
fos.close();
System.out.println( "File 1: '" + fileNameWithPath + "' created." );