itext7 html转pdf 英文或数字不自动换行的问题

本文介绍如何使用iText7和html2pdf库将HTML字符串转换为PDF文件,包括Maven依赖配置、字体设置、字符分割及异常处理等核心代码实现。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.maven jar包依赖

<dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>itext7-core</artifactId>
            <version>7.1.10</version>
            <type>pom</type>
</dependency>
<dependency>
            <groupId>com.itextpdf</groupId>
            <artifactId>html2pdf</artifactId>
            <version>2.1.7</version>
</dependency>

2.核心代码

public static ByteArrayOutputStream htmlToPdf(String htmlStr){
        Document document = null;
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        try {
            PdfDocument pd = new PdfDocument(new PdfWriter(baos));
            document = new Document(pd, PageSize.A3);
            document.setProperty(Property.SPLIT_CHARACTERS, new DefaultSplitCharacters() {
                @Override
                public boolean isSplitCharacter(GlyphLine text, int glyphPos) {
                    //return super.isSplitCharacter(text, glyphPos);//覆盖当前
                    return true;//解决word-break: break-all;不兼容的问题,解决纯英文或数字不自动换行的问题
                }
            });
            DefaultFontProvider defaultFontProvider = new DefaultFontProvider(false, false, false);
            //字体路径
            defaultFontProvider.addFont("./font/NotoSansCJKsc-Regular.otf");
            ConverterProperties c = new ConverterProperties();
            c.setCharset("utf-8");
            c.setFontProvider(defaultFontProvider);
            List<IElement> list = HtmlConverter.convertToElements(htmlStr, c);
            for (IElement ie : list) {
                document.add((IBlockElement) ie);
            }
        } catch (IOException e) {
            log.error("HtmlToPDF 转换pdf失败....",e);
            throw  new BusException();
        } catch (Exception e) {
            log.error("HtmlToPDF 转换pdf失败....", e);
            throw new BusException();
        } finally {
            if (document != null) {
                try {
                    document.close();
                } catch (Exception e) {
                    log.error("document关闭异常...",e);
                    throw new BusException();
                }
            }
        }
        return baos;
    }

 

评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值