JAVA读取和操作PDF系列《五》



bfopdf  创建PDF文件


 前面介绍的iText的确小巧,但是功能也有限制,只能简单的生成PDF文件,BFO却不同,能设置字体、版面等元素。

同样需要导入BFO 架包   http://big.faceless.org/products/bfopdf-2.11.4.zip  或者到 http://url.cn/bPsFWk下载


下面就写上具体代码  

private static PDFStyle numstyle;
private static int pagenum = 1;
private static PDF pdf;
private static final String PAGESIZE = "A4-Landscape";
private static final float WIDTH, HEIGHT;
static {
PDFPage page = new PDFPage(PAGESIZE);
WIDTH = (page.getWidth() / 2) - 100;
HEIGHT = page.getHeight() - 100;
}

public static void main(String args[]) throws IOException {
//并且创建一个PDF对象。
pdf = new PDF();
pdf.setLocale(Locale.CHINA);
// 创建一个新的PDF格式,设置字体(罗马字体)、字号(11)以及颜色(黑色)。
PDFStyle textstyle = new PDFStyle();
textstyle.setFont(new StandardFont(StandardFont.TIMES), 11);
textstyle.setFillColor(Color.black);
textstyle.setTextAlign(PDFStyle.TEXTALIGN_JUSTIFY);
numstyle = new PDFStyle();
numstyle.setFont(new StandardFont(StandardFont.TIMES), 8);
numstyle.setFillColor(Color.black);
numstyle.setTextAlign(PDFStyle.TEXTALIGN_CENTER);
LayoutBox chapter = new LayoutBox(WIDTH);
int chapternumber = 0;
BufferedReader in = new BufferedReader(new FileReader("E:\\bfo.txt"));
String line;
// 文件开始被读取.
while ((line = in.readLine()) != null) {
line = line.trim();
if (line.length() == 0) {
line = "\n\n";
} else {
line += " ";
}
// 调用requote方法。
line = textstyle.getFont().requote(line, pdf.getLocale());
// 开始将内容写进PDF文档。
if (line.startsWith("Chapter ")) {
if (chapternumber > 0) {
writeChapter(chapter, chapternumber);
}
chapternumber++;
chapter = new LayoutBox(WIDTH);
}
chapter.addText(line, textstyle, pdf.getLocale());
}
// 将最后一个段落写入PDF文档
writeChapter(chapter, chapternumber);
OutputStream out = new FileOutputStream("E:\\BFO.pdf");
pdf.render(out);
out.close();
}

private static void writeChapter(LayoutBox chapter, int chapternumber) {
PDFPage page = null;
boolean firstpage = true;
float left;
// 测量文本高度以前,必须清空缓存。
chapter.flush();
while (chapter != null) {
// 清空布局格式。
LayoutBox next = null;
if (chapter.getHeight() > HEIGHT) {
next = chapter.splitAt(HEIGHT);
}
if (pagenum % 2 == 1) {
page = pdf.newPage(PAGESIZE);
left = 50;
// 写下页数。
page.setStyle(numstyle);
page.drawText("Page " + pagenum, page.getWidth() / 4, 30);
page.drawText("Page " + (pagenum + 1), 3 * page.getWidth() / 4,
30);
} else {
left = (page.getWidth() / 2) + 50;
}
page.drawLayoutBox(chapter, left, page.getHeight() - 50);
chapter = next;
pagenum++;
// 如果是第一页的话,添加一个书签。
if (firstpage) {
pdf.getBookmarks().add(new PDFBookmark("Chapter " + chapternumber, PDFAction.goTo(page)));
firstpage = false;
}
}
// 确定下一个段落应该写在剩下的页面。
pagenum |= 1;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值