Java读写pdf文件 在OA业务开发中,经常需要java后台读取或生成pdf文件,itextpdf是一个常用的java操作pdf的开源库 物料准备: 1.引入itextpdf依赖 2.定义Text2
在OA业务开发中,经常需要java后台读取或生成pdf文件,itextpdf是一个常用的java操作pdf的开源库
物料准备:
1.引入itextpdf依赖
2.定义Text2PdfUtil工具类
<dependency> <groupId>com.itextpdfgroupId> <artifactId>itext-asianartifactId> <version>5.2.0version> dependency> <dependency> <groupId>com.itextpdfgroupId> <artifactId>itextpdfartifactId> <version>5.5.13version> dependency>
package cn.ath.knowwikibackend.util;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.PdfReader;import com.itextpdf.text.pdf.PdfWriter;import com.itextpdf.text.pdf.parser.PdfTextExtractor;import java.io.*;import java.NIO.charset.Charset;public class Text2PdfUtil { public static void text2pdf(String text,String pdf) throws DocumentException, IOException { Document doc = new Document(); OutputStream os = new FileOutputStream(new File(pdf)); PdfWriter.getInstance(doc, os); doc.open(); //指定 使用内置的中文字体 BaseFont baseFont = BaseFont.createFont("STSong-Light", "UniGB-UCS2-H", BaseFont.EMBEDDED); Font font = new Font(baseFont,12,Font.NORMAL); //指定输出编码为UTF-8 InputStreamReader isr = new InputStreamReader( new FileInputStream(new File(text)), Charset.forName("UTF-8")); BufferedReader br = new BufferedReader(isr); String str = ""; while((str = br.readLine()) != null){ doc.add(new Paragraph(str,font)); } isr.close(); br.close(); doc.close(); } public static String readPDF(String filename){ StringBuilder result = new StringBuilder(); try { PdfReader reader = new PdfReader(filename); int countPage = reader.getNumberOfPages(); for(int i=1;i<=countPage;i++){ result.append(PdfTextExtractor.getTextFromPage(reader, i)); } reader.close(); } catch (IOException e) { e.printStackTrace(); } return result.toString(); }}
@Test void contextLoads() throws DocumentException, IOException { String txtPath = "E:/test617.txt"; String pdfPath = "E:/test617.pdf"; Text2PdfUtil.text2pdf(txtPath,pdfPath); System.out.println(Text2PdfUtil.readPDF(pdfPath)); }
来源地址:https://blog.csdn.net/ThinkPet/article/details/131256428
--结束END--
本文标题: Java读写pdf文件
本文链接: https://www.lsjlt.com/news/390651.html(转载时请注明来源链接)
有问题或投稿请发送至: 邮箱/279061341@qq.com QQ/279061341
下载Word文档到电脑,方便收藏和打印~
2024-04-03
2024-04-03
2024-04-01
2024-01-21
2024-01-21
2024-01-21
2024-01-21
2023-12-23
回答
回答
回答
回答
回答
回答
回答
回答
回答
回答
0