Search code examples
javamavenpdfflying-saucerxhtmlrenderer

no image displayed using Flying Saucer API in maven project


I am using Flying Saucer API with iText PDF to convert HTML content to PDF.

This requires the following libraries:

  • core-renderer.jar
  • iText-2.0.8.jar

Since the library doesn't support input type checkbox so I am using checkbox image to render in PDF.

However, image is not coming. It is showing nothing.

Resources in flyingsaucer-R8.zip.

Example:

 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." );

Solution

  • Gave the complete path to the image and then it worked.

    I checked this by directly hitting the following URL:

    http://localhost:8001/userApi/resources/images/invoice-bg.jpg
    

    This might help someone if faced with similar issue-

     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." );