- 项目中有的时候需要生成一个这样的PDF表格:
- 一个单元格中包含不同的字体, 实现方式如下:
PDFTest.java
package com.ehi.rc.util.export;
import java.awt.Color;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import com.lowagie.text.Chunk;
import com.lowagie.text.Document;
import com.lowagie.text.DocumentException;
import com.lowagie.text.Font;
import com.lowagie.text.FontFactory;
import com.lowagie.text.PageSize;
import com.lowagie.text.Phrase;
import com.lowagie.text.pdf.PdfPTable;
import com.lowagie.text.pdf.PdfWriter;
public class PDFTest {
Font boldFont = FontFactory
.getFont(FontFactory.HELVETICA, 10, Font.BOLD, Color.BLACK);
Font normalFont = FontFactory
.getFont(FontFactory.HELVETICA, 10, Font.NORMAL, Color.RED);
public byte[] generatePDF() {
// init
Document doc = new Document(PageSize.A4.rotate(), 10f, 10f, 10f, 10f);
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
PdfWriter.getInstance(doc, output);
doc.open();
// create pdf table
PdfPTable pdftable = new PdfPTable(2);
Phrase phrase = new Phrase();
phrase.add(new Chunk("Blod red Font", boldFont));
phrase.add(" : ");
phrase.add(new Chunk("Normal blank Font", normalFont));
pdftable.addCell(phrase);
pdftable.addCell("Another cell");
phrase = new Phrase();
phrase.add(new Chunk("Blod red Font", boldFont));
phrase.add(" : ");
phrase.add(new Chunk("Normal blank Font", normalFont));
pdftable.addCell(phrase);
pdftable.addCell("Another cell");
doc.add(pdftable);
} catch (DocumentException e) {
throw new RuntimeException(e);
} finally {
if (doc.isOpen()) {
doc.close();
}
}
return output.toByteArray();
}
public static void main(String[] args) throws IOException {
File file = new File("D://test.pdf");
FileOutputStream out = new FileOutputStream(file);
out.write(new PDFTest().generatePDF());
}
}
<< IT is an art