IText html到pdf包装线

时间:2017-09-04 21:20:35

标签: java itext

您好我正在使用iText创建javafx应用。我有html编辑器来编写文本,我想从中创建pdf。一切正常但是当我有一个很长的行包含在html编辑器中时,在pdf中它没有包装,它的页面外,我该如何设置包装页面?这是我的代码:

PdfWriter writer = null;
try {
    writer = new PdfWriter("doc.pdf");
} catch (FileNotFoundException e) {
    e.printStackTrace();
}

//Initialize PDF document
PdfDocument pdf = new PdfDocument(writer);

// Initialize document
Document document = new Document(pdf, PageSize.A4);
List<IElement> list = null;
try {
    list = HtmlConverter.convertToElements(editor.getHtmlText());
} catch (IOException e) {
    e.printStackTrace();
}

// add elements to document
for (IElement p : list) {
    document.add((IBlockElement) p);
}

// close document
document.close();

我还想设置此文本的行间距

感谢您的帮助

1 个答案:

答案 0 :(得分:2)

我没有收到以下代码的任何错误:

public class stack_overflow_0008 extends AbstractSupportTicket{

    private static String LONG_PIECE_OF_TEXT = 
        "Once upon a midnight dreary, while I pondered, weak and weary," +
        "Over many a quaint and curious volume of forgotten lore—" +
        "While I nodded, nearly napping, suddenly there came a tapping," +
        "As of some one gently rapping, rapping at my chamber door." +
        "Tis some visitor,” I muttered, “tapping at my chamber door—" +
        "Only this and nothing more.";

    public static void main(String[] args)
    {        

        PdfWriter writer = null;
        try {
            writer = new PdfWriter(getOutputFile());
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //Initialize PDF document
        PdfDocument pdf = new PdfDocument(writer);

        // Initialize document
        Document document = new Document(pdf, PageSize.A4);
        List<IElement> list = null;
        try {
            list = HtmlConverter.convertToElements("<p>" + LONG_PIECE_OF_TEXT + "</p>");
        } catch (IOException e) {
            e.printStackTrace();
        }
        for (IElement p : list) {
            document.add((IBlockElement) p);
        }
        document.close();
    }
}

该文件是单页(A4)PDF,其中一个字符串整齐地包裹着。

我想也许你的字符串的内容是罪魁祸首? 你能发布你从这个编辑器对象得到的HTML吗?

<强>更新

使用此答案中的代码对该问题的新评论中共享的HTML,我得到以下结果:

enter image description here

如您所见,内容分布在两行中。没有内容&#34;从页面上掉下来。&#34;