用itext创建pdf,成为多数企业报表工具的一个首选;
看了itext官方文档,简单的写下笔记:
利用itext生成pdf的步骤:
1:给定一个地址!
2:实例化document对象!
3:取得PdfWriter实例!
4:打开document对象!
5:往document里添加内容!
6:关闭document!
通过以上的简单步骤就可以生成一个pdf!
例如代码:
package com.keith.test;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
public class HelloWorld {
private static final String URL = "/home/core/Desktop/itext_test/hellowold.pdf";
public static void main(String[] args) {
// step 1
Document document = new Document();
try {
// step 2
PdfWriter.getInstance(document, new FileOutputStream(URL));
// step 3
document.open();
// step 4
document.add(new Paragraph("hello wold"));
// step 5
document.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (DocumentException e) {
e.printStackTrace();
}
}
}
来看下如何设置pdf的相关属性:
设置宽度(参考附件里的ItextNarrow.java):
Rectangle pageSize = new Rectangle(216f,720f);
设置pdf的格式为信纸类型这里是(参考附件里的ItextLetter.java):
Document document = new Document(PageSize.LETTER.rotate());
设置odf的页面宽度(参考附件里的ItextLandspace.java):
Document document = new Document(new Rectangle(792,612));
设置顶部和底部的边线(参考附件里的IItextMirroredMarginsTop.java):
document.setMarginMirroringTopBottom(true);
延迟向pdf添加内容(参考附件里的ItextMemory.java):
FileOutputStream fos = new FileOutputStream(URL);
设置odf的格式版本(参考附件里的ItextVersion.java):
writer.setPdfVersion(PdfWriter.VERSION_1_7);
生成zip文件并包含pdf:
ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(URL));
ZipEntry entry = new ZipEntry("hello_" + i + ".pdf");
附件里共享完整的代码!