設定頁面大小及頁面邊界(參數都是float型):
Rectangle pagesize = new Rectangle(200f, 800f); //設定頁面 200*800 單位是使用者顯示單元,預設是1/72英寸。
Document document = new Document(pagesize, 20f, 20f ,20f ,20f); //頁面邊界,順序是左右上下。
自訂使用者顯示單元大小:
PdfWriter writer = PdfWriter.getInstance(document, new FileOutputStream("HelloWorld.pdf"));
writer.setUserunit(72f); //這和上面的配合可以更改實際的頁面大小和邊距。
使用標準頁面格式:
Document document = new Document(PageSize.LETTER); //在 PageSize 類中,包括A0-A10,B0-B10,LETER,LEGAL,LEDGER,TABLOID。
設定大小邊距等屬性的另一種方式:
document.setMargins(10f, 20f, 10f, 20f);//上下左右順序同上
document.setPageSize(PageSize.A5);
模仿實體書橫版邊距對稱(即奇數頁面邊界同 setMargins 中的設定,偶數頁的左右邊距對調,上下邊距不變),或縱版邊距對稱:
document.setMarginMirroring(true);
document.setMarginMirroringTopBottom(true);
先寫進記憶體,最後再輸出:
public static void main(String args[]) throws DocumentException, IOException{
Document document = new Document();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PdfWriter.getInstance(document, baos);
document.open();
document.add(new Paragraph("Hello World!"));
document.close();
FileOutputStream fos = new FileOutputStream("Hello.pdf");
fos.write(baos.toByteArray());
fos.close();
}
另一種方式:
public static void main(String args[]) throws DocumentException,
IOException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream("HelloWorld1.pdf"));
document.open();
PdfContentByte canvas = writer.getDirectContentUnder();
writer.setCompressionLevel(0);//設定壓縮等級,0為不壓縮,可以用文字編輯器直接看到內容。
canvas.saveState();
canvas.beginText();
canvas.moveText(30, 180);//文本初始位置左位移和上位移
canvas.setFontAndSize(BaseFont.createFont(), 12);
canvas.showText("Hello world!");
canvas.endText();
canvas.restoreState();
document.close();
}
將“Hello world!”作為短語插入(效果同上):
public static void main(String args[]) throws DocumentException,
IOException {
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document,
new FileOutputStream("HelloWorld1.pdf"));
document.open();
PdfContentByte canvas = writer.getDirectContentUnder();
writer.setCompressionLevel(0);// 設
Phrase hello = new Phrase("Hello world!");
//下面這句的意思是將短句 hello 變數中的文字,以靠左對齊的方式,添加到畫布 canvas 變數中,
//座標位置為(30,180),旋轉角度為0。
ColumnText.showTextAligned(canvas, Element.ALIGN_LEFT, hello, 30, 180, 0);
document.close();
}
建立 n 個文檔並將它們儲存到壓縮包中:
public static void main(String args[]) throws DocumentException,
IOException {
ZipOutputStream zip = new ZipOutputStream(new FileOutputStream(
"test.zip"));
for (int i = 0; i ZipEntry entry = new ZipEntry("hello" + i + ".pdf"); zip.putNextEntry(entry);
Document document = new Document();
PdfWriter writer = PdfWriter.getInstance(document, zip);
writer.setCloseStream(false);//如果不這麼做,在第一次迴圈中就會自動關閉zip的輸出資料流。
document.open();
document.add(new Paragraph("Hello world " + i)); document.close();
zip.closeEntry();
}
zip.close();
}