Aggiungi testo al PDF tramite C#

Aggiungi testo al documento PDF con .NET. Usa Aspose.PDF per modificare i documenti PDF a livello di codice

Come lavorare con il testo in un PDF utilizzando la libreria .NET

Per aggiungere testo al file PDF, useremo l’API Aspose.PDF for .NET, un’API di manipolazione di documenti ricca di funzionalità, potente e facile da usare per .NET. Apri il gestore di pacchetti NuGet, cerca Aspose.pdf e installa. È inoltre possibile utilizzare il seguente comando dalla console di Package Manager.

Package Manager Console

PM > Install-Package Aspose.PDF

Aggiungi testo al file PDF tramite C#


Per provare il codice nel proprio ambiente, è necessario Aspose.PDF for .NET.

  1. Carica il PDF con un’istanza di Document.
  2. Crea un TextParagraph e definisci le sue proprietà.
  3. Aggiungi il TextParagraph alla pagina usando TextBuilder.
  4. Salvate nuovamente il file.

Aggiungi testo al PDF - C#

Questo codice di esempio mostra come aggiungere testo in un documento PDF - C#

var inputFile = Path.Combine(dataDir, "sample.pdf");
var outputFile = Path.Combine(dataDir, "sample_out.pdf");
var pdfDocument = new Aspose.Pdf.Document(inputFile);
var page = pdfDocument.Pages[1];

var textFragment = new Aspose.Pdf.Text.TextFragment("Lorem ipsum")
{
    Position = new Aspose.Pdf.Text.Position(100, 600)
};
        
textFragment.TextState.FontSize = 12;
textFragment.TextState.Font = Aspose.Pdf.Text.FontRepository.FindFont("TimesNewRoman");
textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.LightGray;
textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.Red;

var textBuilder = new Aspose.Pdf.Text.TextBuilder(page);
textBuilder.AppendText(textFragment);
pdfDocument.Save(outputFile);