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();
}
}