多格式转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