Cómo Dibujar Líneas y Rectángulos en PDFs en C#

How to Draw Lines and Rectangles on PDFs

This article was translated from English: Does it need improvement?
Translated
View the article in English

Drawing lines and rectangles onto a PDF document refers to the process of adding geometric shapes, specifically lines and rectangles, to the content of a PDF file. This is often done programmatically using a programming language like C# or VB.NET and a library like IronPDF.

When you draw a line, you create a visible line segment with specified starting and ending points. Similarly, when you draw a rectangle, you define a four-sided shape with specified dimensions and positions.

Quickstart: Draw Lines and Rectangles with IronPDF

Effortlessly enhance your PDF documents by drawing lines and rectangles using IronPDF. This quick guide demonstrates how to use the DrawLine method for lines and the DrawRectangle method for rectangles. With just a few lines of code, you can create dynamic graphical elements in your PDFs, making it easy to add professional-quality visuals to your applications. Follow along to get started instantly.

Nuget IconGet started making PDFs with NuGet now:

  1. Install IronPDF with NuGet Package Manager

    PM > Install-Package IronPdf

  2. Copy and run this code snippet.

    IronPdf.PdfDocument pdf = IronPdf.PdfDocument.FromFile("input.pdf");
    pdf.DrawLine(10, 10, 200, 10, "#FF0000", 2);
    pdf.SaveAs("output.pdf");
  3. Deploy to test on your live environment

    Start using IronPDF in your project today with a free trial
    arrow pointer


Draw Line Example

By utilizing the DrawLine method available for the PdfDocument object, you can add lines to an existing PDF. Using the Color class offered by IronDrawing API Documentation opens up the possibility to apply a line with a color from a HEX color code.

:path=/static-assets/pdf/content-code-examples/how-to/draw-line-and-rectangle-draw-line.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>testing</h1>");

// Configure the required parameters
int pageIndex = 0;
var start = new IronSoftware.Drawing.PointF(200,150);
var end = new IronSoftware.Drawing.PointF(1000,150);
int width = 10;
var color = new IronSoftware.Drawing.Color("#000000");

// Draw line on PDF
pdf.DrawLine(pageIndex, start, end, width, color);

pdf.SaveAs("drawLine.pdf");
Imports IronPdf

Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>testing</h1>")

' Configure the required parameters
Private pageIndex As Integer = 0
Private start = New IronSoftware.Drawing.PointF(200,150)
Private [end] = New IronSoftware.Drawing.PointF(1000,150)
Private width As Integer = 10
Private color = New IronSoftware.Drawing.Color("#000000")

' Draw line on PDF
pdf.DrawLine(pageIndex, start, [end], width, color)

pdf.SaveAs("drawLine.pdf")
$vbLabelText   $csharpLabel

Output PDF

Draw Rectangle Example

To add rectangles to PDFs, use the DrawRectangle method. Once the PDF document is opened or rendered, this method is available for the PdfDocument object. Easily configure the coordinates, width, and height for the rectangle with the RectangleF class offered by IronDrawing API Documentation.

:path=/static-assets/pdf/content-code-examples/how-to/draw-line-and-rectangle-draw-rectangle.cs
using IronPdf;

ChromePdfRenderer renderer = new ChromePdfRenderer();
PdfDocument pdf = renderer.RenderHtmlAsPdf("<h1>testing</h1>");

// Configure the required parameters
int pageIndex = 0;
var rectangle = new IronSoftware.Drawing.RectangleF(200, 100, 1000, 100);
var lineColor = new IronSoftware.Drawing.Color("#000000");
var fillColor = new IronSoftware.Drawing.Color("#32AB90");
int lineWidth = 5;

// Draw rectangle on PDF
pdf.DrawRectangle(pageIndex, rectangle, lineColor, fillColor, lineWidth);

pdf.SaveAs("drawRectangle.pdf");
Imports IronPdf

Private renderer As New ChromePdfRenderer()
Private pdf As PdfDocument = renderer.RenderHtmlAsPdf("<h1>testing</h1>")

' Configure the required parameters
Private pageIndex As Integer = 0
Private rectangle = New IronSoftware.Drawing.RectangleF(200, 100, 1000, 100)
Private lineColor = New IronSoftware.Drawing.Color("#000000")
Private fillColor = New IronSoftware.Drawing.Color("#32AB90")
Private lineWidth As Integer = 5

' Draw rectangle on PDF
pdf.DrawRectangle(pageIndex, rectangle, lineColor, fillColor, lineWidth)

pdf.SaveAs("drawRectangle.pdf")
$vbLabelText   $csharpLabel

Output PDF

Preguntas Frecuentes

¿Cómo dibujar líneas en PDFs usando C#?

Para dibujar líneas en PDFs usando C#, utiliza el método DrawLine del objeto PdfDocument en IronPDF. Este método te permite especificar los puntos de inicio y fin de la línea, así como aplicar colores usando códigos HEX con la API IronDrawing.

¿Cuáles son los pasos para dibujar rectángulos en documentos PDF con C#?

Primero, descarga la librería IronPDF de NuGet. Luego, importa o renderiza el documento PDF de destino. Usa el método DrawRectangle para agregar rectángulos definiendo coordenadas, ancho y alto con la clase RectangleF. Finalmente, exporta el documento PDF editado.

¿Puedo usar VB.NET para dibujar formas en un PDF?

Sí, puedes usar VB.NET para dibujar formas en un PDF. IronPDF soporta tanto C# como VB.NET, permitiéndote utilizar métodos como DrawLine y DrawRectangle para agregar líneas y rectángulos a tus documentos PDF.

¿Cómo aplicar color a las líneas en un PDF usando C#?

En C#, puedes aplicar color a las líneas en un PDF usando la clase Color en combinación con el método ColorTranslator.FromHtml para especificar un código de color HEX. Esto se utiliza dentro del método DrawLine de IronPDF.

¿Dónde puedo encontrar documentación detallada para dibujar líneas y rectángulos?

La documentación detallada para dibujar líneas y rectángulos usando IronPDF se puede encontrar en la [Documentación de la API IronDrawing](https://ironsoftware.com/open-source/csharp/drawing/docs/). Proporciona guías y ejemplos comprensivos para utilizar funcionalidades de dibujo.

¿Es posible editar un PDF existente para agregar formas geométricas con C#?

Sí, es posible editar un PDF existente para agregar formas geométricas con C#. Usando IronPDF, puedes renderizar un PDF y usar métodos como DrawLine y DrawRectangle para integrar líneas y rectángulos programáticamente.

¿Cómo puedes exportar un PDF después de agregar líneas y rectángulos?

Después de agregar líneas y rectángulos a un PDF usando IronPDF, puedes exportar el documento modificado utilizando el método SaveAs del objeto PdfDocument, especificando la ruta de salida del archivo deseada.

¿Cuáles son los requisitos previos para usar IronPDF en un proyecto C#?

Para usar IronPDF en un proyecto C#, necesitas descargar e instalar la librería IronPDF de NuGet. Asegúrate de que tu entorno de desarrollo soporte lenguajes .NET como C# o VB.NET.

¿IronPDF es compatible con .NET 10? ¿Hay algún cambio al dibujar líneas o rectángulos en proyectos .NET 10?

Sí, IronPDF es totalmente compatible con .NET 10, así como con .NET 9, 8, 7, 6 y versiones anteriores. No hay cambios importantes para dibujar líneas o rectángulos al migrar a .NET 10; los métodos de la API de IronDrawing, DrawLine y DrawRectangle funcionan igual que en versiones anteriores. La información de compatibilidad de IronPDF confirma que funciona de inmediato en proyectos .NET 10.

Chaknith Bin
Ingeniero de Software
Chaknith trabaja en IronXL e IronBarcode. Tiene un profundo conocimiento en C# y .NET, ayudando a mejorar el software y apoyar a los clientes. Sus conocimientos derivados de las interacciones con los usuarios contribuyen a mejores productos, documentación y experiencia en general.
¿Listo para empezar?
Nuget Descargas 16,154,058 | Versión: 2025.11 recién lanzado