Draw a rectangle in a PDF document using iText
51,252
Solution 1
Here is the solution. Thanks Dylan McClung.
PdfWriter writer = ...;
PdfContentByte cb = writer.getDirectContent();
cb.saveState();
cb.setColorStroke(Color.black);
cb.rectangle(x,y,x1,y1);
cb.stroke();
cb.restoreState();
Solution 2
A more complete example is at: http://www.mikesdotnetting.com/Article/88/iTextSharp-Drawing-shapes-and-Graphics
Solution 3
In the .NET version I just create a table with a border. I know it isn't Java but maybe the following code will help you.
iTextSharp.text.Document document = new iTextSharp.text.Document(PageSize.LETTER, 20, 20, 20, 20);
PdfPTable table;
PdfPCell cell;
// single element w/ border
table = new PdfPTable(1);
cell = new PdfPCell(new Phrase("BOLD WORDS", FontFactory.GetFont(FontFactory.HELVETICA_BOLD, 11, Font.BOLD)));
cell.BorderWidth = 2;
cell.Padding = 5;
cell.PaddingTop = 3;
cell.HorizontalAlignment = Element.ALIGN_CENTER;
table.AddCell(cell);
table.SetWidthPercentage(new float[1] { 598f }, PageSize.LETTER);
table.HorizontalAlignment = Element.ALIGN_CENTER;
document.Add(table);
Solution 4
public static void drawRectangle(PdfContentByte content, float width, float height) {
content.saveState();
PdfGState state = new PdfGState();
state.setFillOpacity(0.6f);
content.setGState(state);
content.setRGBColorFill(0xFF, 0xFF, 0xFF);
content.setLineWidth(3);
content.rectangle(0, 0, width, height);
content.fillStroke();
content.restoreState();
}
From API of itext
Author by
Paolo Dragone
University of Nebraska at Kearney Professor. Husker fan at heart.
Updated on July 09, 2022Comments
-
Paolo Dragone almost 2 years
Is there a way in iText to draw a rectangle in a PDF document?
-
Chris623 over 10 yearsthe idea just drawing a table cell is not that bad
-
Amedee Van Gasse over 8 years
PdfContentByte cb = writer.getDirectContent();