Trabalhe com texto em PDF via Python

Como trabalhar com texto em PDF usando a biblioteca Python for .NET

Como trabalhar com texto em PDF usando a biblioteca Python for .NET

Para adicionar texto ao arquivo PDF, usaremos a API Aspose.PDF para Python, 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.

Python Package Manager Console

pip install aspose-pdf

Adicionar texto ao arquivo PDF via Python


Para testar o código em seu ambiente, você precisa do Aspose.PDF para Python.

  1. Carregue o PDF com uma instância do Document.
  2. Crie um TextParagraph e defina suas propriedades.
  3. Adicione o TextParagraph à página usando o TextBuilder.
  4. Salve o arquivo novamente.

Adicione texto ao PDF - Python

<% text.code-block.subtitle %>


    // 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);