itextpdf实现text文本转pdf

itextpdf实现word转pdf

此处用到了windows的字体,windows字体放在了resources目录下
windows字体路径:C:\Windows\Fonts
在这里插入图片描述
在这里插入图片描述

import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;

import java.io.*;


/********************************************
 * Copyright © 2022,
 * All Rights Reserved.
 * 摘 要: [简要描述本文件的内容]
 * @Author: lkl
 * @date: 2023-02-15
 ********************************************/
public class TextTurnPdf {
    private static final String FONT = "/static/font/simhei.ttf";
    /**
     *
     * text转pdf
     * @param: textFilePath 文件路径
     * @param: pdfOutputPath 输出路径
     * @return:
     */
    public static void textPdf(String textFilePath, String pdfOutputPath) throws DocumentException, IOException {
        //创建pdf文档
        Document document = new Document();
        //将pdf输出到指定路径
        OutputStream os = new FileOutputStream(new File(pdfOutputPath));
        //初始化 pdf输出对象
        PdfWriter.getInstance(document, os);
        //打开pdf文档
        document.open();
        //使用Windows系统字体(TrueType)
        BaseFont baseFont = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
        Font font = new Font(baseFont);
        //输入流读取器读取word文档中的内容
        InputStreamReader isr = new InputStreamReader(new FileInputStream(new File(textFilePath)), "UTF-8");
        //将读取的内容存放在BufferedReader
        BufferedReader bufferedReader = new BufferedReader(isr);
        String str = "";
        //循环一行一行读取缓存中的内容,并且添加到pdf文档中
        while ((str = bufferedReader.readLine()) != null) {
            document.add(new Paragraph(str, font));
        }
        //关闭pdf文档
        document.close();
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值