Created
January 12, 2017 15:40
-
-
Save syakovyn/6ead2da4f00716b25a4803e36b64bb90 to your computer and use it in GitHub Desktop.
Shows a case of a wrong line-height interpretation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package html_to_pdf; | |
import com.lowagie.text.Chunk; | |
import com.lowagie.text.Document; | |
import com.lowagie.text.DocumentException; | |
import com.lowagie.text.Element; | |
import com.lowagie.text.List; | |
import com.lowagie.text.ListItem; | |
import com.lowagie.text.Paragraph; | |
import com.lowagie.text.html.simpleparser.HTMLWorker; | |
import com.lowagie.text.html.simpleparser.StyleSheet; | |
import com.lowagie.text.pdf.PdfPCell; | |
import com.lowagie.text.pdf.PdfPTable; | |
import com.lowagie.text.pdf.PdfWriter; | |
import java.io.FileOutputStream; | |
import java.io.IOException; | |
import java.io.StringReader; | |
public class LineHeightIssue { | |
private static final String HTML = "<p>Title</p><p style=\"line-height:2\">Testing text</p>"; | |
public static void main(String args[]) throws DocumentException, IOException { | |
FileOutputStream out = new FileOutputStream("test.pdf"); | |
Document document = new Document(); | |
PdfWriter pdfWriter = PdfWriter.getInstance(document, out); | |
document.open(); | |
PdfPTable table = getPdfPTable(); | |
document.add(table); | |
document.close(); | |
} | |
private static PdfPTable getPdfPTable() throws IOException { | |
PdfPTable table = new PdfPTable(1); | |
table.addCell(getGoodPdfPCell()); | |
table.addCell(getBadPdfPCell()); | |
return table; | |
} | |
/* | |
* Everything is fine. Applied a workaround to fix the leading. | |
*/ | |
private static PdfPCell getGoodPdfPCell() throws IOException { | |
PdfPCell cell = new PdfPCell(); | |
java.util.List<?> list = HTMLWorker.parseToList(new StringReader(HTML), new StyleSheet()); | |
list.forEach(element -> { | |
if (element instanceof Paragraph) { | |
final Paragraph paragraph = (Paragraph) element; | |
if (paragraph.getMultipliedLeading() == 0 && paragraph.getLeading() < paragraph.getFont() | |
.getCalculatedSize()) { | |
paragraph.setMultipliedLeading(paragraph.getLeading()); | |
} | |
} | |
cell.addElement((Element) element); | |
}); | |
return cell; | |
} | |
/* | |
* Shows a case of a wrong line-height interpretation. The paragraphs overlaps. | |
*/ | |
private static PdfPCell getBadPdfPCell() throws IOException { | |
PdfPCell cell = new PdfPCell(); | |
java.util.List<?> list = HTMLWorker.parseToList(new StringReader(HTML), new StyleSheet()); | |
list.forEach(element -> cell.addElement((Element) element)); | |
return cell; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment