iText Convert HTML with Images to PDF in Java Example Tutorial

In the previous post, we provided a basic example for converting a HTML file to PDF Document. The HTML file we used did not contain any images.That throws an interesting question; will the same code work if my HTML Document contained some images? Or, how do I convert a HTML document containing images to PDF file? The good news for us is that the same code we presented in the tutorial earlier, would also work in this case and we can get a good looking PDF file with images as an output. This tutorial explains how to go about on converting a HTM file that contains pictures to PDF. Before you begin, I would recommend reading the first tutorial linked above as it would serve as the foundation for this tutorial.

Step -1: The input HTML file will have an image now. Refer to the sample HTML code below, you can use this if you want; or write your own.
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" 
   "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <title>Example To Convert HTML File with Images to PDF Using Java iText</title>
        <style type="text/css"> b { color: green; } </style>
    </head>
    <body>        
            <b>Transform HTML document with Pictures</b>
            We have converted a HTML File with Images to PDF document Using Java!!
     <br/>
     <!-- This section adds an image to the file -->
     <b>Let us add an image to the HTML Document </b>
     <img src="load.jpg"></img>
    </body>
</html>
The image file load.jpg is shown below if you want to reuse.Also, note that I have added a comment in my HTML code. You will find that the final PDF document automatically remove this.
Convert HTML with Images to PDF Using Java
Convert HTML with Images to PDF using Java
You will not have to change your Java code from what you had in the first tutorial. The same code will make sure that the HTML document with images is converted into a PDF. The alignment will differ for now as our HTML is not aligned properly. We will see how to fix this in some of our advanced tutorials on conversion. A screen dump of the converted PDF document is shown below. (and it contains the images we used)
PDF File holding HTML Document with Images
Screenshot of the PDF file with image added

1 comment:

  1. U told image will come in pdf but not happening coz image is not in src folder. I have some issue when it comes from within img tag.

    ReplyDelete