[英]add border to pdf page using itext
這是我的源代碼。 為什么即使啟用了所有邊界的邊框后,我仍無法在pdf頁面中添加邊框? 我已經設置了邊框及其顏色,但仍然無法添加邊框。
void create() throws DocumentException,IOException{
// step 1
Document document = new Document();
// step 2
PdfWriter writer=PdfWriter.getInstance(document, new FileOutputStream(RESULT));
document.setPageSize(PageSize.LETTER);
document.setMargins(36, 72, 108, 180);
document.setMarginMirroring(false);
// step 3
document.open();
// step 4
Rectangle rect= new Rectangle(36,108);
rect.enableBorderSide(1);
rect.enableBorderSide(2);
rect.enableBorderSide(4);
rect.enableBorderSide(8);
rect.setBorder(2);
rect.setBorderColor(BaseColor.BLACK);
document.add(rect);
Font font = new Font(Font.FontFamily.TIMES_ROMAN, 26, Font.UNDERLINE, BaseColor.BLACK);
Paragraph title= new Paragraph("CURRICULUM VITAE\n\n",font);
title.setAlignment(Element.ALIGN_CENTER);
document.add(title);
Font f1= new Font (Font.FontFamily.UNDEFINED, 13, Font.NORMAL, BaseColor.BLACK);
Paragraph info= new Paragraph("Name\n\nEmail\n\nContact Number",f1);
Paragraph addr= new Paragraph("Street\n\nCity\n\nPin",f1);
PdfPTable table = new PdfPTable(2);
table.setWidthPercentage(100);
table.spacingAfter();
PdfPCell cell = new PdfPCell(info);
cell.setHorizontalAlignment(Element.ALIGN_LEFT);
cell.disableBorderSide(Rectangle.BOX);
cell.setExtraParagraphSpace(1.5f);
table.addCell(cell);
cell = new PdfPCell(addr);
cell.setHorizontalAlignment(Element.ALIGN_RIGHT);
cell.disableBorderSide(Rectangle.BOX);
cell.setExtraParagraphSpace(1.5f);
table.addCell(cell);
document.add(table);
document.add(new Chunk("\n"));
document.add(new LineSeparator(2f,100,BaseColor.DARK_GRAY,Element.ALIGN_CENTER,-1f));
您可以通過添加以下內容來修復(1.):
rect.setBorder(Rectangle.BOX);
rect.setBorderWidth(2);
請注意,我將刪除enableBorderSide()
調用。 您會注意到您以錯誤的方式使用了setBorder()
方法。
要解決(2.),我將使用page事件。 請注意,您不能在頁面事件中使用document.add()
,因此您必須執行DrawRectangle
示例中所述的操作,以回答iText問題:PdfContentByte.rectangle(Rectangle)不起作用符合預期
創建Document
對象時,您沒有定義頁面大小,這意味着iText將使用PageSize.A4
。 幾行之后,您將使用PageSize.LETTER
。 這些值是不可變的Rectangle
對象。 您可以使用PageSize.A4
的尺寸/坐標(或者您的情況: PageSize.LETTER
)創建一個新的Rectangle
。 您可以使用getWidth()
和getHeight()
方法獲取尺寸,並使用getLeft()
, getBottom()
, getRight()
和getTop()
獲得坐標。
Rectangle rect= new Rectangle(577,825,18,15); // you can resize rectangle
rect.enableBorderSide(1);
rect.enableBorderSide(2);
rect.enableBorderSide(4);
rect.enableBorderSide(8);
rect.setBorderColor(BaseColor.BLACK);
rect.setBorderWidth(1);
document.add(rect);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.