I have searched the questions and have not been able to find a solution to my specific problem. What I need to do is convert HTML files that contain images and CSS styling to PDF. I am using iText 5 and have been able to include the styling into the generated PDF. However, I am still struggling including the images. I have included my code below. The image with the absolute path is included in the generated PDF, the image with the relative path is not. I know I need to implement AbstractImageProvider, but I do not know how to do it. Any help is greatly appreciated.
Java File:
public class Converter {
static String in = "C:/Users/APPS/Desktop/Test_Html/index.htm";
static String out = "C:/Users/APPS/Desktop/index.pdf";
static String css = "C:/Users/APPS/Desktop/Test_Html/style.css";
public static void main(String[] args) {
try {
convertHtmlToPdf();
} catch (DocumentException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
private static void convertHtmlToPdf() throws DocumentException, IOException {
Document document = new Document();
PdfWriter pdfWriter = PdfWriter.getInstance(document, new FileOutputStream(out));
document.open();
XMLWorkerHelper.getInstance().parseXHtml(pdfWriter, document, new FileInputStream(in), new FileInputStream(css));
document.close();
System.out.println("PDF Created!");
}
/**
* Not sure how to implement this
* @author APPS
*
*/
public class myImageProvider extends AbstractImageProvider {
@Override
public String getImageRootPath() {
// TODO Auto-generated method stub
return null;
}
}
}
Html File:
<!DOCTYPE html>
<html lang="en">
<head>
<title>HTML to PDF</title>
<link href="style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h1>HTML to PDF</h1>
<p>
<span class="itext">itext</span> 5.4.2
<span class="description"> converting HTML to PDF</span>
</p>
<table>
<tr>
<th class="label">Title</th>
<td>iText - Java HTML to PDF</td>
</tr>
<tr>
<th>URL</th>
<td>http://wwww.someurl.com</td>
</tr>
</table>
<div class="center">
<h2>Here is an image</h2>
<div>
<img src="images/Vader_TFU.jpg" />
</div>
<div>
<img src="https://www.w3schools.com/images/picture.jpg" alt="Mountain" />
</div>
</div>
</body>
</html>
Css File:
h1 {
color: #ccc;
}
table tr td {
text-align: center;
border: 1px solid gray;
padding: 4px;
}
table tr th {
background-color: #84C7FD;
color: #fff;
width: 100px;
}
.itext {
color: #84C7FD;
font-weight: bold;
}
.description {
color: gray;
}
.center {
text-align: center;
}
The following is based on iText5 5.5.12 version
Suppose you have this directory structure:
With this code and using latest iText5:
And here is the result:
This example uses code from: https://developers.itextpdf.com/examples/xml-worker-itext5/xml-worker-examples
Hope this helps