Cómo dibujar texto y mapa de bits en PDFs en C#

How to Draw Text and Bitmap on PDFs

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

Drawing text and images on a PDF involves adding text and images to an existing document. IronPDF seamlessly enables this feature. By incorporating text and images, users can customize PDFs with watermarks, logos, and annotations, improving the document's visual appearance and branding. Additionally, text and images facilitate the presentation of information, data visualization, and the creation of interactive forms.

Quickstart: Add Text and Images to PDFs with IronPDF

Get started with IronPDF by enhancing your PDF documents with text and images quickly and efficiently. Using the DrawText and DrawBitmap methods, you can easily customize your PDFs, whether adding watermarks, logos, or annotations. This example shows how to draw text at specific coordinates and insert an image seamlessly into your PDF, offering a streamlined approach to document customization. Perfect for developers looking to improve branding or visual appeal in their applications.

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.

    new ChromePdfRenderer()
        .RenderHtmlAsPdf("<h1>Doc</h1>")
        .DrawText("Hello World", FontTypes.TimesNewRoman.Name, 12, 0, 100, 100, Color.Black, 0)
        .DrawBitmap(AnyBitmap.FromFile("logo.png"), 0, 50, 250, 500, 300)
        .SaveAs("annotated.pdf");
  3. Deploy to test on your live environment

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


Draw Text on PDF Example

By utilizing the DrawText method available for the PdfDocument object, you can add text to an existing PDF without altering its original content.

:path=/static-assets/pdf/content-code-examples/how-to/draw-text-and-bitmap-draw-text.cs
using IronPdf;
using IronSoftware.Drawing;

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

// Draw text on PDF
pdf.DrawText("Some text", FontTypes.TimesNewRoman.Name, FontSize: 12, PageIndex: 0, X: 100, Y: 100, Color.Black, Rotation: 0);

pdf.SaveAs("drawText.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Available Fonts in FontTypes Class

The DrawText method currently supports all Standard Fonts in IronPDF, including Courier, Arial (or Helvetica), Times New Roman, Symbol, and ZapfDingbats. Visit the 'Standard Fonts in IronPDF' section in the Manage Fonts article for italic, bold, and oblique variants of these font types.

The ZapfDingbats font, in particular, can be used to display symbols such as ▲ . For a comprehensive list of supported symbols, you can visit Wikipedia on Zapf Dingbats.

Output fonts sample on PDF

Fonts Sample on PDF

Draw Text with Newline

The draw text action supports newline characters, allowing you to render text with built-in newlines for better formatting and visual clarity.

To achieve this, add newline characters (\n) to the text string. Using the example above, you can draw:

string textWithNewlines = "Some text\nSecond line";
pdfDoc.DrawText(textWithNewlines, font, position);
string textWithNewlines = "Some text\nSecond line";
pdfDoc.DrawText(textWithNewlines, font, position);
Imports Microsoft.VisualBasic

Dim textWithNewlines As String = "Some text" & vbLf & "Second line"
pdfDoc.DrawText(textWithNewlines, font, position)
$vbLabelText   $csharpLabel

Use Custom Font

We also support using custom fonts with the DrawText method; below is an example with the Pixelify Sans Font added for the text.

:path=/static-assets/pdf/content-code-examples/how-to/draw-text-and-bitmap-draw-custom-font.cs
using IronPdf;
using IronSoftware.Drawing;
using System.IO;

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

// Add custom font to the PDF
byte[] fontByte = File.ReadAllBytes(@".\PixelifySans-VariableFont_wght.ttf");
var addedFont = pdf.Fonts.Add(fontByte);

// Draw text on PDF
pdf.DrawText("Iron Software", addedFont.Name, FontSize: 12, PageIndex: 0, X: 100, Y: 600, Color.Black, Rotation: 0);

pdf.SaveAs("drawCustomFont.pdf");
Imports IronPdf
Imports IronSoftware.Drawing
Imports System.IO

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

' Add custom font to the PDF
Private fontByte() As Byte = File.ReadAllBytes(".\PixelifySans-VariableFont_wght.ttf")
Private addedFont = pdf.Fonts.Add(fontByte)

' Draw text on PDF
pdf.DrawText("Iron Software", addedFont.Name, FontSize:= 12, PageIndex:= 0, X:= 100, Y:= 600, Color.Black, Rotation:= 0)

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

Draw Image Example

With IronPDF's DrawBitmap method, you can easily add bitmaps to an existing PDF document. This method functions similarly to the Image Stamper feature, allowing you to stamp images onto an existing PDF.

Por favor notaThe DrawBitmap method works best with large images. When attempting to use smaller resolution images, you may encounter the following exception: IronPdf.Exceptions.IronPdfNativeException: 'Error while drawing image: data length (567000) is less than expected (756000)'. To overcome this issue, you can use the Image Stamper, which seamlessly handles images of all sizes.

Sample image

1200 x 627 image

Code

:path=/static-assets/pdf/content-code-examples/how-to/draw-text-and-bitmap-draw-bitmap.cs
using IronPdf;
using IronSoftware.Drawing;

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

// Open the image from file
AnyBitmap bitmap = AnyBitmap.FromFile("ironSoftware.png");

// Draw the bitmp on PDF
pdf.DrawBitmap(bitmap, 0, 50, 250, 500, 300);

pdf.SaveAs("drawImage.pdf");
IRON VB CONVERTER ERROR developers@ironsoftware.com
$vbLabelText   $csharpLabel

Output PDF

DrawBitmap Additional Parameters

  • PixelFormat: The PixelFormat property specifies the color data format for the bitmap, primarily controlling its support for transparency. The default value is Format32bppArgb. Developers can choose between the pixel enum formats Format32bppRgb and Format32bppArgb by passing the parameter in as an option.

  • IgnorePageRotation: This bool property dictates whether, when drawing the bitmap, the method ignores the page rotation or not. By default, the value is false. Especially useful in scenarios where you have to apply a watermark consistently to all pages, regardless of rotation.

Ready to see what else you can do? Check out our tutorial page here: Edit PDFs

Preguntas Frecuentes

¿Cómo puedo dibujar texto y una imagen en PDFs usando C#?

Puedes usar el método DrawText de IronPDF para añadir texto a un PDF y el método DrawBitmap para añadir imágenes. Primero, descarga la biblioteca IronPDF desde NuGet, importa tu PDF, aplica el texto o imagen, y exporta el documento editado.

¿Qué fuentes son compatibles al añadir texto a un PDF?

IronPDF es compatible con fuentes estándar como Courier, Arial (Helvetica), Times New Roman, Symbol y ZapfDingbats. También puedes usar fuentes personalizadas especificando el archivo de la fuente personalizada al usar el método DrawText.

¿Cómo añado texto a un PDF con saltos de línea usando C#?

Para añadir texto con saltos de línea en IronPDF, incluye caracteres de nueva línea ('\n') en tu cadena de texto al usar el método DrawText. Esto te permite formatear el texto para mayor claridad y organización.

¿Puedo usar fuentes personalizadas en mis documentos PDF?

Sí, IronPDF es compatible con fuentes personalizadas. Puedes especificar un archivo de fuente personalizado al usar el método DrawText para incluir tipografía única en tus PDFs.

¿Qué debo hacer si encuentro un error al dibujar imágenes en un PDF?

Si encuentras errores, especialmente con imágenes pequeñas, considera usar la función Image Stamper de IronPDF, que maneja imágenes de todos los tamaños sin problemas y previene excepciones comunes.

¿Cómo puedo convertir HTML a PDF en C#?

Puedes usar el método RenderHtmlAsPdf de IronPDF para convertir cadenas de HTML en PDFs. También puedes convertir archivos HTML a PDFs usando RenderHtmlFileAsPdf.

¿Cómo empiezo a usar IronPDF para editar PDFs?

Comienza descargando la biblioteca de IronPDF desde NuGet. Luego, importa el documento PDF deseado, usa los métodos DrawText o DrawBitmap para agregar texto o imágenes, y finalmente exporta el documento editado.

¿IronPDF es totalmente compatible con .NET 10 para dibujar texto e imágenes?

Sí, IronPDF funciona de inmediato con .NET 10. Es compatible con todas sus versiones principales, incluyendo .NET 10, sin necesidad de soluciones alternativas. Puede usar métodos como DrawText y DrawBitmap en aplicaciones .NET 10 igual que en versiones anteriores. La compatibilidad de IronPDF con .NET 10 está confirmada explícitamente en la documentación del producto.

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