How to Draw Rectangle in PDF by Using C#/VB.NET
Sometimes, we need to draw some shapes in PDF according to document contents. Actually, there are too many shapes we can draw and the most frequently used shapes are geometric figures. In the last post, I have introduced a method about how to draw circle in PDF and now I want to share method to draw rectangle (one kind of shapes) in PDF by using C#/VB.NET.
I will draw two rectangles in a new PDF document and set format for them. When drawing rectangle, we need to pay attention to the following items, rectangle location and size (width and height). About format, for the first one, I set color for its borders, while the second one, I set its background color.
Note: Spire.PDF is used for realizing this function, so I have added its dll file as reference. Also, system.drawing should be as reference for color setting.
STEPS
Step 1. Create PDF and Add Page
Declare a new PDF document and add page for this document.
C#
PdfDocument document = new PdfDocument();
PdfPageBase page = document.Pages.Add();
VB.NET
Dim document As New PdfDocument()
Dim page As PdfPageBase = document.Pages.Add()
Step 2. Set Pen and Brush
Declare a new PDF pen which is used to set borders color and line width. The, declare a new PDF brush which is used to set background color of rectangle.
C#
PdfPen pen = new PdfPen(Color.DarkOliveGreen, 0.7f);
PdfBrush brush = new PdfSolidBrush(Color.DeepSkyBlue);
VB.NET
Dim pen As New PdfPen(Color.DarkOliveGreen, 0.7F)
Dim brush As PdfBrush = New PdfSolidBrush(Color.DeepSkyBlue)
Step 3. Draw Rectangle
Use page.Canvas.DrawRectangle() method to draw rectangles. When drawing the first, pass three parameters, pen, rectangle location (x, y) and rectangle size (height and width). When drawing the second, change parameter pen as brush and define new location for it.
C#
page.Canvas.DrawRectangle(pen, new Rectangle(new Point(100, 20), new Size(100, 100)));
page.Canvas.DrawRectangle(brush, new RectangleF(new Point(300, 20), new SizeF(100, 100)));
VB.NET
page.Canvas.DrawRectangle(pen, New Rectangle(New Point(100, 20), New Size(100, 100)))
page.Canvas.DrawRectangle(brush, New RectangleF(New Point(300, 20), New SizeF(100, 100)))
Step 4. Save and Launch
Save this document with a file name and then launch it.
C#
document.SaveToFile("Rectangle.pdf");
System.Diagnostics.Process.Start("Rectangle.pdf");
VB.NET
document.SaveToFile("Rectangle.pdf")
System.Diagnostics.Process.Start("Rectangle.pdf")
RESULT
______________________________________________________________________________________________
Click Here to LEARN MORE about Spire.PDF
Click Here to DOWNLOAD Spire.PDF
Spire.Office also can be used to realize this function.