多格式转pdf——txt转pdf

复制代码
 1     public static String txtToPdfConverter(String txtFilePath, String pdfFilePath, String fontPath) throws Exception {
 2         // 创建Document对象
 3         Document document = new Document();
 4         // 创建PdfWriter对象将文档写入文件
 5         PdfWriter.getInstance(document, new FileOutputStream(pdfFilePath));
 6         // 打开文档
 7         document.open();
 8         // 设置字体,用于支持中文显示
 9         fontPath = fontPath + ",0";
10 //        System.out.println(fontPath);
11         BaseFont font = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
12         Font chineseFont = new Font(font, 12);
13         // 创建BufferedReader对象来读取文件
14         BufferedReader reader = new BufferedReader(new FileReader(urlToFile(new URL(txtFilePath))));
15         String line;
16         while ((line = reader.readLine()) != null) {
17             Paragraph paragraph = new Paragraph(line, chineseFont);
18             // 添加文本内容到文档
19             document.add(paragraph);
20         }
21         reader.close();
22         document.close();
23         //本地上传oss
24         return pdfFilePath;
25     }
复制代码

 

复制代码
 1     public static File urlToFile(URL url) {
 2         InputStream is = null;
 3         File file = null;
 4         FileOutputStream fos = null;
 5         try {
 6             file = File.createTempFile("tmp", null);
 7             URLConnection urlConn = null;
 8             urlConn = url.openConnection();
 9             is = urlConn.getInputStream();
10             fos = new FileOutputStream(file);
11             byte[] buffer = new byte[4096];
12             int length;
13             while ((length = is.read(buffer)) > 0) {
14                 fos.write(buffer, 0, length);
15             }
16             return file;
17         } catch (IOException e) {
18             return null;
19         } finally {
20             if (is != null) {
21                 try {
22                     is.close();
23                 } catch (IOException e) {
24                 }
25             }
26             if (fos != null) {
27                 try {
28                     fos.close();
29                 } catch (IOException e) {
30                 }
31             }
32         }
33     }
复制代码

 多格式转换相关:https://www.cnblogs.com/Rover20230226/p/17786602.html

posted @   青核桃啊  阅读(22)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」
点击右上角即可分享
微信分享提示