您的位置:首页 > 编程语言 > Java开发

Java中iText使用技巧

2008-03-26 16:04 543 查看
要生成pdf文件,在网上查了下资料,首选iText,跟着大家走,我也iText一把。

1:把字型编程A4横向

Document document = new Document(PageSize.A4.rotate());


2:在PDF文件中加入表格

float[] widths = {0.05f,0.29f, 0.05f, 0.05f, 0.14f, 0.03f, 0.04f,0.04f, 0.05f, 0.05f,0.08f,0.08f, 0.05f};
//new 一个13列的table
PdfPTable table = new PdfPTable(13);
//设置table每一列的宽度,widths里写的是百分比,他们加和需要是1
table.setWidths(widths);
//设置表格在页面上的宽度,设成100表示可以表格填满页面,但是要去掉页面margin
table.setWidthPercentage(100);
//设置表格上端的空白距离,类似css中的margin-top:xxpx;这样在给表格加上标题后,标题就不会跟表格重叠在一起了。
table.setSpacingBefore(3f);


3:向表格里填数据, 例子

for(int i = 0; i<26; i++)
{
table.table.addCell(i+"");
}


这样就会往表格里填上2行数据,这个api比较简单,不用向jxl/poi 那里那样还有明确写出到底要往那个cell填

4:标题和表格组合

document.add(new Paragraph(titleWorkhour, FontFactory.getFont(FontFactory.HELVETICA, 12, Font.BOLD, new Color(0, 0, 0))));
//由于设置了table.setSpacingBefore(3f);所以table跟标题不会重合。
document.add(table);


5:分页

document.newPage();


6:合并PDF文件,由于往一个document里加内容只能是顺序往下加,而我的summary页要最后才能算出来,但是summary页又要放在第一页

所以我不得不先把body生成一个pdf文件,然后summary在生成一个文件,然后把两个文件合并成同一个文件。

private void concatenateSummary(String[] args, String finalFile)
{
try {
int pageOffset = 0;
ArrayList master = new ArrayList();
int f = 0;
String outFile = finalFile;
Document document = null;
PdfCopy  writer = null;
while (f < args.length) {
// we create a reader for a certain document
PdfReader reader = new PdfReader(args[f]);
reader.consolidateNamedDestinations();
// we retrieve the total number of pages
int n = reader.getNumberOfPages();
List bookmarks = SimpleBookmark.getBookmark(reader);
if (bookmarks != null) {
if (pageOffset != 0)
SimpleBookmark.shiftPageNumbers(bookmarks, pageOffset, null);
master.addAll(bookmarks);
}
pageOffset += n;
if (f == 0) {
// step 1: creation of a document-object
document = new Document(reader.getPageSizeWithRotation(1));
// step 2: we create a writer that listens to the document
writer = new PdfCopy(document, new FileOutputStream(outFile));
// step 3: we open the document
document.open();
}
// step 4: we add content
PdfImportedPage page;
for (int i = 0; i < n; ) {
++i;
page = writer.getImportedPage(reader, i);
writer.addPage(page);
}
PRAcroForm form = reader.getAcroForm();
if (form != null)
writer.copyAcroForm(reader);
f++;
}
if (!master.isEmpty())
writer.setOutlines(master);
// step 5: we close the document
document.close();
}
catch(Exception e) {
e.printStackTrace();
}
}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: