六狼论坛

 找回密码
 立即注册

QQ登录

只需一步,快速开始

新浪微博账号登陆

只需一步,快速开始

搜索
查看: 116|回复: 0

iText 创建 PDF

[复制链接]

升级  33.33%

24

主题

24

主题

24

主题

秀才

Rank: 2

积分
100
 楼主| 发表于 2013-2-7 19:37:47 | 显示全部楼层 |阅读模式
前些日子搞  doc 转 PDF.头大.没什么进展.今天把PDF 看了一下.方法许多,选了这一种.
这些解决方案不完整.好烦.
package com.isw2.pdf.test;import java.io.File;import java.io.FileNotFoundException;import java.io.FileOutputStream;import java.io.FileReader;import java.io.IOException;import java.io.OutputStream;import java.util.ArrayList;import java.util.Date;import com.lowagie.text.Document;import com.lowagie.text.DocumentException;import com.lowagie.text.Element;import com.lowagie.text.Font;import com.lowagie.text.Paragraph;import com.lowagie.text.html.simpleparser.HTMLWorker;import com.lowagie.text.html.simpleparser.StyleSheet;import com.lowagie.text.pdf.BaseFont;import com.lowagie.text.pdf.PdfWriter;public class TestPDF {public static void main(String[] args) {// createPDFbyIText("good good study ,day day up!好好学习,天天向上!",// "C:/test/test.pdf");createPDFbyHTML("c:/test/good.html", "C:/test/test.pdf");}/** * HTML 方式写入 PDF .(本人暂时不能解决中言乱码问题) * @param htmlContent * @param outPath */public static void createPDFbyHTML(String htmlContent, String outPath) {try {StyleSheet st = new StyleSheet();st.loadTagStyle("body", "leading", "16,0");BaseFont bfTitle = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);Font titleFont = new Font(bfTitle, 18, Font.NORMAL);Document document = new Document();PdfWriter.getInstance(document, new FileOutputStream(outPath));document.open();ArrayList list = HTMLWorker.parseToList(new FileReader(htmlContent), st);for (Object object : list) {document.add((Element) object);}document.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (DocumentException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}/** * 写入 PDF 文件. * @param content * @param outPath */public static void createPDFbyIText(String content, String outPath) {try {//字体BaseFont bfTitle = BaseFont.createFont("STSong-Light","UniGB-UCS2-H", BaseFont.NOT_EMBEDDED);Font titleFont = new Font(bfTitle, 18, Font.NORMAL);OutputStream outputStream = new FileOutputStream(new File(outPath));Document document = new Document();PdfWriter.getInstance(document, outputStream);document.open();document.add(new Paragraph(content, titleFont));// 设置字体可解决中方问题document.add(new Paragraph("\n 你一定可以."));// 中文无法正常显示document.add(new Paragraph(new Date().toString()));document.addAuthor("zhouxianglh");document.addTitle("good study");document.close();outputStream.close();} catch (FileNotFoundException e) {e.printStackTrace();} catch (DocumentException e) {e.printStackTrace();} catch (IOException e) {e.printStackTrace();}}} 
 
今天也小郁闷,犯了两个错误.老大很生气.一个是用了过时的方法,第二个是代码晦涩.优秀是一种习惯.要好好加油呀.才刚刚开始.冯晶晶那也在搞这,搞的咋样了?在想.学习不能止步.好好加油!
您需要登录后才可以回帖 登录 | 立即注册 新浪微博账号登陆

本版积分规则

快速回复 返回顶部 返回列表