Как вставить новый абзац в существующий PDF-файл с помощью C# и .NET

  1. Добавьте SautinSoft.Document из Nuget.
  2. Загрузите документ.
  3. Найдите все абзацы по центру.
  4. Установите для него желтый фон.
  5. Сохраните документ.

Полный код

using System;
using System.IO;
using System.Linq;
using SautinSoft.Document;

namespace Example
{
    class Program
    {
        static void Main(string[] args)
        {
            // Get your free 30-day key here:   
            // https://sautinsoft.com/start-for-free/

            InsertParagraph();
        }
        /// <summary>
        /// Inserts a new paragraph into an existing PDF document.
        /// </summary>
        /// <remarks>
        /// Details: https://sautinsoft.com/products/document/help/net/developer-guide/insert-paragraphs-to-pdf-document-net-csharp-vb.php
        /// </remarks>
        static void InsertParagraph()
        {
            string inpFile = @"..\..\..\example.pdf";
            string outFile = @"Result.pdf";

            DocumentCore dc = DocumentCore.Load(inpFile);
            Paragraph p = new Paragraph(dc);
            p.Content.Start.Insert("Alexander Pushkin was a great russian romantic poet " +
                "and writer who is considered by a lot of people as the best russian poet and the founder " +
                "of contemporary russian literature.",
                new CharacterFormat() { Size = 20, FontName = "Verdana", FontColor = new Color("#358CCB") });
            p.ParagraphFormat.Alignment = HorizontalAlignment.Justify;

            // Insert the paragraph as 1st element in the 1st section.
            dc.Sections[0].Blocks.Insert(0, p);

            dc.Save(outFile);
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });

        }
    }
}

Download

Imports System
Imports System.IO
Imports System.Linq
Imports SautinSoft.Document

Namespace Example
    Friend Class Program
        Shared Sub Main(ByVal args() As String)
            InsertParagraph()
        End Sub
        ''' Get your free 30-day key here:   
        ''' https://sautinsoft.com/start-for-free/
        ''' <summary>
        ''' Inserts a new paragraph into an existing PDF document.
        ''' </summary>
        ''' <remarks>
        ''' Details: https://sautinsoft.com/products/document/help/net/developer-guide/insert-paragraphs-to-pdf-document-net-csharp-vb.php
        ''' </remarks>
        Private Shared Sub InsertParagraph()
            Dim inpFile As String = "..\..\..\example.pdf"
            Dim outFile As String = "Result.pdf"

            Dim dc As DocumentCore = DocumentCore.Load(inpFile)
            Dim p As New Paragraph(dc)
            p.Content.Start.Insert("Alexander Pushkin was a great russian romantic poet " & "and writer who is considered by a lot of people as the best russian poet and the founder " & "of contemporary russian literature.", New CharacterFormat() With {
                .Size = 20,
                .FontName = "Verdana",
                .FontColor = New Color("#358CCB")
            })
            p.ParagraphFormat.Alignment = HorizontalAlignment.Justify

            ' Insert the paragraph as 1st element in the 1st section.
            dc.Sections(0).Blocks.Insert(0, p)

            dc.Save(outFile)
            System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})

        End Sub
    End Class
End Namespace

Download


Если вам нужен пример кода или у вас есть вопрос: напишите нам по адресу [email protected] или спросите в онлайн-чате (правый нижний угол этой страницы) или используйте форму ниже:



Вопросы и предложения всегда приветствуются!

Мы разрабатываем компоненты .Net с 2002 года. Мы знаем форматы PDF, DOCX, RTF, HTML, XLSX и Images. Если вам нужна помощь в создании, изменении или преобразовании документов в различных форматах, мы можем вам помочь. Мы напишем для вас любой пример кода абсолютно бесплатно.