最近在做一个文档转pdf 在线浏览的功能,office 文档使用LibreOffice工具用java 成功实现了转换,txt也可以实现转换 但是存在中文乱码问题没有找到解决方法(如果有大神知道望指教),但想到字符可以保存成的pdf,那么我把txt读取成字符串然后再转为pdf不就行了吗?经过尝试发现的确可行,代码如下:
package com.office.OpenOffice;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Font;
import com.itextpdf.text.PageSize;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.BaseFont;
import com.itextpdf.text.pdf.PdfWriter;
/**
* @author:WHW
* @CreateTime:2019年6月12日
**/
public class TxtTopdf {
public static void main(String[] args) {
String pdfurl="D:/htmTopdf/ITextUtil.pdf";//保存路径
String path="D:/htmTopdf/55.txt";
generatePdfFile(pdfurl, DocumentToString(path));
}
/**
* 文档转string
*/
public static String DocumentToString(String path) {
File file = new File(path);
String str = "";
try {
FileInputStream in = new FileInputStream(file);
// size 为字串的长度 ,这里一次性读完
int size = in.available();
byte[] buffer = new byte[size];
in.read(buffer);
in.close();
str = new String(buffer, "GB2312");
return str;
} catch (Exception e) {
return null;
}
}
/**
* String生成PDF文件
*/
public static void generatePdfFile(String pdfurl, String content) {
Rectangle rectPageSize = new Rectangle(PageSize.A4);// A4纸张
Document document = new Document(rectPageSize, 40, 40, 40, 40);// 上、下、左、右间距
try {
// 创建一个PdfWriter实例,将文件输出流指向一个文件
PdfWriter.getInstance(document, new FileOutputStream(pdfurl));
// 打开文档。
document.open();
// 解决中文乱码,我这用到windos中的字体
document.add(new Paragraph(content, new Font(
BaseFont.createFont("C:\\WINDOWS\\Fonts\\SIMFANG.TTF", BaseFont.IDENTITY_H, BaseFont.EMBEDDED), 10,
Font.NORMAL)));
} catch (DocumentException de) {
System.err.println(de.getMessage());
} catch (IOException ioe) {
System.err.println(ioe.getMessage());
}
// 关闭文档。
document.close();
}
}