Search code examples
javaitextpdfhtml

How to avoid unwanted white space getting add in PDF generated using pdfHtml?


I'm using pdfHtml of iText to generate PDF from HTML, but I can see lots of white spaces has got added in between two elements in generated PDF.

Please see below HTML and PDF

Highlighted part in below image shows unwanted white spaces in between two lines.

space between two below lines .

Below is the source HTML content.

 <html>
 <head></head>
 <body>  
  <meta name="generator" content="HTML Tidy for Java (vers. 2009-12-01), see jtidy.sourceforge.net"> 
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> 
  <style type="text/css">
 * { font-family: 'Arial Unicode MS'; } 
    </style> 
  <title></title>   
  <img border="0" style="margin-left: 370px;" width="340.6" src="file:Docs_a0s29000000qTxeAAE/01529000000ITQ8.PNG">  
  <div style="font-size: 25px; font-family: Roboto, arial, sans-serif;">
   สวัสดีชาวโลก!
  </div> 
  <div style="font-size: 25px; font-family: Roboto, arial, sans-serif;">
   นี่คือเทมเพลตการปฏิเสธความรับผิด!
  </div> 
  <ul> 
   <li>BioConnect Version 1 - Capture</li> 
  </ul>  
  <p> <span style="font-size: 25px; font-family: Roboto, arial, sans-serif;">嘿!这是结算模板</span> </p> 
  <div style="margin-right: 500px;">
   中文1 
   <img border="0" src="null" style="margin-right: 500px;" width="112.5"> 
   <br>中文2 
   <br>中文3 
   <br>中文4 
   <br>中文5 
   <br>中文6
  </div>   
 </body>
</html>

Here is HTML looks like in browser.

HTML looks perfect in browser

Any comments/ Solutions would be appreciated. Thanks


Solution

  • If I understand you correctly, you complain about the leading (default space between lines) which iText uses for your html.

    In comparison to browsers by default iText considers the ascender and descender stored in a font file to calculate the leading between the lines. It seems that they are rather big for the font iText uses to process your html and that causes the issue.

    To overcome it, one can play with line-height property. I believe that setting its value as 1em would help you.

    I've added the next css style rule to your html file:

    div {
        line-height: 1em;
    }
    

    Then I've used the latest iText7 (7.1.5-SNAPSHOT both for itextcore and html2pdf) and processed your html both before and after my change. Now please look at the results

    New html: https://pastebin.com/tFzdViyx

    Before: enter image description here

    After: enter image description here

    Comparison: enter image description here