Para adicionar texto ao arquivo PDF, usaremos a API Aspose.PDF para .NET, que é uma API de manipulação de documentos rica em recursos, poderosa e fácil de usar para .NET. Abra o gerenciador de pacotes NuGet, pesquise Aspose.pdf e instale. Você também pode usar o seguinte comando no Console do Gerenciador de Pacotes.
PM > Install-Package Aspose.PDF
Adicionar texto ao arquivo PDF via C#
Para testar o código em seu ambiente, você precisa do Aspose.PDF para .NET.
- Carregue o PDF com uma instância do Document.
- Crie um TextParagraph e defina suas propriedades.
- Adicione o TextParagraph à página usando o TextBuilder.
- Salve o arquivo novamente.
Adicione texto ao PDF - C#
// Open document
Document pdfDocument = new Document(dataDir + "input.pdf");
// Get particular page
Page pdfPage = (Page)pdfDocument.Pages[1];
// Create text fragment
TextFragment textFragment = new TextFragment("main text");
textFragment.Position = new Position(100, 600);
// Set text properties
textFragment.TextState.FontSize = 12;
textFragment.TextState.Font = FontRepository.FindFont("TimesNewRoman");
textFragment.TextState.BackgroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.LightGray);
textFragment.TextState.ForegroundColor = Aspose.Pdf.Color.FromRgb(System.Drawing.Color.Red);
// Create TextBuilder object
TextBuilder textBuilder = new TextBuilder(pdfPage);
// Append the text fragment to the PDF page
textBuilder.AppendText(textFragment);
dataDir = dataDir + "AddText_out.pdf";
// Save resulting PDF document.
pdfDocument.Save(dataDir);