Java实现Txt转PDF文件
Posted Henu丶雨巷
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Java实现Txt转PDF文件相关的知识,希望对你有一定的参考价值。
TxT转PDF可以直接使用IText就可以了,IText在pdf领域可以说暂时是最好的方案了。通过直接读取txt文件,然后生成pdf,再添加文本就可以了。
代码如下:
public class Txt2PDF { private static final String FONT = "C:\Windows\Fonts\simhei.ttf"; public static void text2pdf(String text, String pdf) throws DocumentException, IOException { Document document = new Document(); OutputStream os = new FileOutputStream(new File(pdf)); PdfWriter.getInstance(document, os); document.open(); //方法一:使用Windows系统字体(TrueType) 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(); } public static void main(String[] args) throws Exception { String PDFTIMEDIR = "F:/pdf/"; String text = PDFTIMEDIR + "1.txt"; String pdf = PDFTIMEDIR + "1.txt.pdf"; text2pdf(text, pdf); } }
simhei.ttf字体可从网上进行下载
项目中使用:
package com.ksource.pwlp.util; import java.io.BufferedReader; import java.io.File; import java.io.FileOutputStream; import java.io.InputStream; import java.io.InputStreamReader; import java.io.OutputStream; import javax.servlet.http.HttpServletRequest; import com.ksource.core.fastdfs.FastDfsUtil; import com.ksource.core.fastdfs.FileResponseData; import com.lowagie.text.Document; import com.lowagie.text.Font; import com.lowagie.text.Paragraph; import com.lowagie.text.pdf.BaseFont; import com.lowagie.text.pdf.PdfWriter; /** * 文本文件转pdf并上传到fastDFS * 并返回相应的参数 * @author dxy * */ public class TxtToPdf { public FileResponseData txtToPdf(HttpServletRequest request, InputStream is, String pdf) throws Exception { String fontPath = request.getSession().getServletContext().getRealPath("/assets/vendor/font-awesome/fonts/simhei.ttf"); Document document = new Document(); OutputStream os = new FileOutputStream(new File(pdf)); PdfWriter.getInstance(document, os); document.open(); BaseFont baseFont = BaseFont.createFont(fontPath, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED); Font font = new Font(baseFont); InputStreamReader isr = new InputStreamReader(is, "GBK"); BufferedReader bufferedReader = new BufferedReader(isr); String str = ""; while ((str = bufferedReader.readLine()) != null) { document.add(new Paragraph(str, font)); } document.close(); FileResponseData fileResponseData = FastDfsUtil.uploadToServerByPath(pdf); File file = new File(pdf); if(file.exists()){ file.delete(); } return fileResponseData; } }
以上是关于Java实现Txt转PDF文件的主要内容,如果未能解决你的问题,请参考以下文章