0

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." );
sjain
  • 23,126
  • 28
  • 107
  • 185

3 Answers3

0

You should use the latest version of Flying-Saucer (currently 9.1.9). You can find with on mvnrepository.

You should also check that the file images/invoice-bg.jpg exists and is accessible from the root of your project.

If your path is correct, the generated PDF will contain your image.

obourgain
  • 8,856
  • 6
  • 42
  • 57
  • Actually, I am getting image with a simple java project but when I use maven project then image is not coming in PDF. So it is not a Flying-Saucer version problem. It is related to maven location. Do I need to put images folder location in my `pom.xml`? My maven project has images which are in `resources/images` folder. – sjain Dec 18 '17 at 16:52
0

If you use resources with relative file paths, you will need to specify a base URL in the setDocument call.

Daniel F
  • 509
  • 4
  • 7
0

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." );
sjain
  • 23,126
  • 28
  • 107
  • 185