txt转化为PDF

一、采用Txt/Word/Excel/PPT=>PDF(OpenOffice+JodConverter)=>SWF(pdf2swf)=>FlexPaper浏览方式
二、将txt转化为PDF,需要用到iText.jar包
package com.converter;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;

import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Element;
import com.lowagie.text.Font;
import com.lowagie.text.PageSize;
import com.lowagie.text.Paragraph;
import com.lowagie.text.pdf.BaseFont;
import com.lowagie.text.pdf.PdfWriter;

/**
 * 将从.txt中读到的内容写到pdf中。
 * */
public class TXT2PDF {
	private final static String READFILEPATH = "C:\\wroking\\1.txt"; // txt文件
	private final static String WRITEFILEPATH = "C:\\wroking\\1.pdf"; // 生成的pdf文件

	public static void main(String[] args) throws DocumentException,IOException {
		Document document = new Document(PageSize.A4, 80, 80, 60, 30);
		PdfWriter.getInstance(document, new FileOutputStream(WRITEFILEPATH));
		document.open();
		String a = BaseFont.IDENTITY_H;
		BaseFont bfChinese = BaseFont.createFont("C:/WINDOWS/Fonts/SIMYOU.TTF", BaseFont.IDENTITY_H,BaseFont.NOT_EMBEDDED);//"UniGB-UCS2-H"
		Font FontChinese = new Font(bfChinese, 18, Font.NORMAL);
		Paragraph t = new Paragraph("oracle手册", FontChinese); // 起一个别名。
		t.setAlignment(Element.ALIGN_CENTER);
		t.setLeading(30.0f);
		document.add(t);
		FontChinese = new Font(bfChinese, 11, Font.NORMAL);
		BufferedReader read = null;
		InputStream in=null;
		InputStream inn=null;
		try {
			in = new FileInputStream(READFILEPATH);
			byte[] b = new byte[4];
			in.read(b);
			in.close();
			inn  = new FileInputStream(READFILEPATH);
			String code = codeType(b);
			read = new BufferedReader(new InputStreamReader(inn, code));// 编码转换
			String line = null;
			while ((line = read.readLine()) != null) {
				System.out.println(line);
				t = new Paragraph(line,FontChinese);
				t.setAlignment(Element.ALIGN_LEFT);
				t.setLeading(20.0f);
				document.add(t);
			}
		} catch (Exception e) {
			System.out.println("目标文件不存,或者不可读!");
			e.printStackTrace();
		} finally {
			try {
				inn.close();
				read.close();
				document.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		System.out.println("============执行成功!===========");
	}

	/**
	 * byte[] head:表示txt文件的字节数组
	 */
	public static String codeType(byte[] head) {
		byte[] codehead = new byte[4];
		// 截取数组
		System.arraycopy(head, 0, codehead, 0, 4);
		String code = "";
		if (head[0] == -1 && head[1] == -2) {
			code = "UTF-16";
		} else if (head[0] == -2 && head[1] == -1) {
			code = "Unicode";
		} else if (head[0] == -17 && head[1] == -69 && head[2] == -65)
			code = "UTF-8";
		else {
			code = "GBK";
		}
		return code;
	}
}

你可能感兴趣的:(pdf)