When we write an article, we may need to insert some special symbols, such as triangle, star, arrow and so on. In this post, I will talk something about how to draw shape in PDF with C#.
In my example, I will draw stars and add colors for them on one blank PDF page. Actually, stars can be regard as being formed with five isosceles triangles around a pentagon. I will just add colors on triangles for the second star and have a color gradient effect with whole star for the third star. Then, the following steps will show details.
Before starting with steps, I need to add two references in my project. One is system.drawing and the other is Spire.PDF which I use to meet my requirement.
1. Create a PDF document and add one page.
2. Define a method DrawPath to draw stars with colors to be convenient for using in main method.
- For draw stars, we need to define 5 points and set their locations firstly. Then, add lines to connect them together.
- Save graphics. Firstly, set format, including pen and brush colors. Secondly, set shapes scale and location. Then, draw the first star with format. Thirdly, draw the second star. Set location according to first star location. Then, set its fill mode and draw it with format. Finally, draw the third star as drawing the second star.
- Restore graphics.
3. Use DrawPath method in main method and then save and launch file.
static void Main(string args)
PdfDocument doc = new PdfDocument();
PdfPageBase page = doc.Pages.Add();
private static void DrawPath(PdfPageBase page)
PointF points = new PointF;
for (int i = 0; i < points.Length; i++)
float x = (float)Math.Cos(i * 2 * Math.PI / 5);
float y = (float)Math.Sin(i * 2 * Math.PI / 5);
points[i] = new PointF(x, y);
PdfPath path = new PdfPath();
PdfGraphicsState state = page.Canvas.Save();
PdfPen pen = new PdfPen(Color.LightSeaGreen, 0.015f);
PdfBrush brush1 = new PdfSolidBrush(Color.MediumTurquoise);
path.FillMode = PdfFillMode.Alternate;
page.Canvas.DrawPath(pen, brush1, path);
= new PdfLinearGradientBrush(new PointF(-2, 0), new PointF(2, 0), Color.LimeGreen, Color.AliceBlue);
path.FillMode = PdfFillMode.Winding;
page.Canvas.DrawPath(pen, brush2, path);
Result Shown by Following:
Click Here to Learn more about Spire.PDF
Click Here to Download Spire.PDF