itext7不会破坏长网址

时间:2018-03-07 17:40:16

标签: html pdf itext

我正在尝试从HTML生成PDF文件。我在HTML代码中有两个长URL。问题是只有一个URL(longURL2)被拆分为下一行。另一个网址(longURL)超出了页边距。有人可以帮我弄清楚为什么iText不会分割其他网址吗?

我的代码:

String longURL = "http://localhost/erp/process/see_process.jsp?vp=ATENDING_PROCESS_EMPLOYEE&tr=1493131180671041&ev=1520277948136217";
String longURL2 = "https://stackoverflow.com/questions/48422409/how-to-set-pdf-page-size-a4-when-we-use-itextrenderer-to-generate-pdf-from-thyme";

String htmlCode = 
              "<p align=\"right\">City Name - March, 5 \r\n2018.</p>"
            + "<p>&nbsp;</p>"
            + "<p>&nbsp;Lorem ipsum dolor sit amet, consectetur adipiscing elit. Vivamus sollicitudin consectetur vulputate. "
            + "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Interdum et malesuada fames ac ante ipsum primis in faucibus."
            + "<br/><br/></p>"
            + "<p>" + longURL + "</p>"
            + "<p>" + longURL2 + "</p>"
            + "<p>&nbsp;</p>"
            + "<p>&nbsp;</p><center>"
            + "<p><b>My First Name \r\nLast Name</b><br>My Department</p>"
            + "</center>";

File dest = new File("C:/Temp/target_pdf_file.pdf");

PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
pdf.setDefaultPageSize(PageSize.A4);

ConverterProperties converterProperties = new ConverterProperties();
FontProvider dfp = new DefaultFontProvider(true, true, true);
converterProperties.setFontProvider(dfp);

HtmlConverter.convertToPdf(htmlCode, pdf, converterProperties);

1 个答案:

答案 0 :(得分:0)

这是我已经找到的解决方案。问题是iText用来分割线条的字符。它不使用“_”之类的字符。所以,首先,有必要添加这个角色。一个好方法是扩展类DefaultSplitCharacters。代码如下:

public class CustomSplitCharacters extends DefaultSplitCharacters {

    @Override
    public boolean isSplitCharacter(GlyphLine text, int glyphPos) {

        if (super.isSplitCharacter(text, glyphPos)) return true;

        int charCode = text.get(glyphPos).getUnicode();

        return (charCode == '_' || charCode == '&' || charCode == '?' ||
                charCode == '='); 
    }
}

请注意,我添加了一些额外的拆分字符:"&", "?" and "="

第二步是使用HtmlConverter生成pdf。代码如下:

    File dest = new File("C:/Temp/target_pdf_file.pdf");

    PdfDocument pdf = new PdfDocument(new PdfWriter(dest));
    pdf.setDefaultPageSize(PageSize.A4);

    ConverterProperties converterProperties = new ConverterProperties();
    FontProvider dfp = new DefaultFontProvider(true, true, true);
    converterProperties.setFontProvider(dfp);
    converterProperties.setImmediateFlush(false);

    Document doc = HtmlConverter.convertToDocument(htmlCode, pdf , converterProperties);
    doc.setProperty(Property.SPLIT_CHARACTERS, new CustomSplitCharacters());
    doc.relayout();

    doc.close();