java实现在线预览txt转pdf
首先引入itext的jar包
<dependency>
<groupId>com.itextpdf</groupId>
<artifactId>itextpdf</artifactId>
<version>5.5.13.1</version>
</dependency>
传入txt和pdf路径,设置pdf中字体
public class Fileconversion {
private static final String FONT = "C:\\Windows\\Fonts\\STFANGSO.TTF";
public static void texttopdf(String text, String pdf) throws DocumentException, IOException {
Document document = new Document();
OutputStream os = new FileOutputStream(new File(pdf));
PdfWriter.getInstance(document, os);
document.open();
BaseFont baseFont = BaseFont.createFont(FONT, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
Font font = new Font(baseFont);
InputStreamReader isr = new InputStreamReader(new FileInputStream(new File(text)), "GBK");
BufferedReader bufferedReader = new BufferedReader(isr);
String str = "";
while ((str = bufferedReader.readLine()) != null) {
document.add(new Paragraph(str, font));
}
document.close();
}