Как удалить верхний или нижний колонтитул в PDF-файле на C# и .NET

  1. Добавьте SautinSoft.Document из Nuget.
  2. Загрузите PDF-документ.
  3. Выполните итерацию по разделам и удалите первый абзац.
  4. Сохраните документ.

Часто у нас есть документы, в которые необходимо внести какие-либо правки. Например, удалить старый заголовок и вставить вместо него новый!

В PDF ссылке нет понятия верхнего/нижнего колонтитула.
При загрузке документа в DocumentCore - верхний/нижний колонтитул записываются в начало коллекции блоков разделов (Sections.Blocks).
Этот пример кода поможет Вам изменить заголовок в существующем PDF-файле.

Для примера: У нас есть PDF файл и нам нужно удалить старый Header: "Created : 20 January 2019" и вставить новый Header: " Modified : 1 April 2020"

HeaderFooter header = new HeaderFooter(dc, HeaderFooterType.HeaderDefault);
header.Content.Start.Insert("Modified : 1 April 2020", new CharacterFormat() { Size = 14.0, FontColor = Color.DarkGreen });
      foreach (Section s in dc.Sections)
       {
         if (s.Blocks.Count > 0)
             s.Blocks.RemoveAt(0);
         s.HeadersFooters.Add(header.Clone(true));
       }

 

Здесь Вы можете скачать исходный PDF файл и выходной результат

Полный код

using System.IO;
using SautinSoft.Document;

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

            ReplaceHeader();
        }

        /// <summary>
        /// Removes the old header/footer and inserts a new one into an existing PDF document.
        /// </summary>
        /// <remarks>
        /// Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/remove-header-and-footer-in-pdf-net-csharp-vb.php
        /// </remarks>
        static void ReplaceHeader()
        {
            string inpFile = @"..\..\..\somebody.pdf";
            string outFile = "With new Header.pdf";
            DocumentCore dc = DocumentCore.Load(inpFile);

            // Create new header with formatted text.
            HeaderFooter header = new HeaderFooter(dc, HeaderFooterType.HeaderDefault);
            header.Content.Start.Insert("Modified : 1 April 2020", new CharacterFormat() { Size = 14.0, FontColor = Color.DarkGreen });
            // Add 10 mm from Top before new header.
            (header.Blocks[0] as Paragraph).ParagraphFormat.SpaceBefore = LengthUnitConverter.Convert(10, LengthUnit.Millimeter, LengthUnit.Point);


            foreach (Section s in dc.Sections)
            {
                // Find the first paragraph (Let's assume that it's the header) and remove it.
                if (s.Blocks.Count > 0)
                    s.Blocks.RemoveAt(0);
                // Insert the new header into the each section.
                s.HeadersFooters.Add(header.Clone(true));                
            }

            dc.Save(outFile);

            // Open the results for demonstration purposes.
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(inpFile) { UseShellExecute = true });
            System.Diagnostics.Process.Start(new System.Diagnostics.ProcessStartInfo(outFile) { UseShellExecute = true });

        }
    }
}

Download

Imports System
Imports System.IO
Imports SautinSoft.Document

Module Sample
    Sub Main()
        ReplaceHeader()
    End Sub
    ''' Get your free 30-day key here:   
    ''' https://sautinsoft.com/start-for-free/
    ''' <summary>
    ''' Removes the old header/footer and inserts a new one into an existing PDF document.
    ''' </summary>
    ''' <remarks>
    ''' Details: https://www.sautinsoft.com/products/document/help/net/developer-guide/remove-header-and-footer-in-pdf-net-csharp-vb.php
    ''' </remarks>
    Sub ReplaceHeader()
        Dim inpFile As String = "..\..\..\somebody.pdf"
        Dim outFile As String = "With new Header.pdf"
        Dim dc As DocumentCore = DocumentCore.Load(inpFile)

        ' Create new header with formatted text.
        Dim header As New HeaderFooter(dc, HeaderFooterType.HeaderDefault)
        header.Content.Start.Insert("Modified : 1 April 2020", New CharacterFormat() With {
                .Size = 14.0,
                .FontColor = Color.DarkGreen
            })
        ' Add 10 mm from Top before new header.
        TryCast(header.Blocks(0), Paragraph).ParagraphFormat.SpaceBefore = LengthUnitConverter.Convert(10, LengthUnit.Millimeter, LengthUnit.Point)


        For Each s As Section In dc.Sections
            ' Find the first paragraph (Let's assume that it's the header) and remove it.
            If s.Blocks.Count > 0 Then
                s.Blocks.RemoveAt(0)
            End If
            ' Insert the new header into the each section.
            s.HeadersFooters.Add(header.Clone(True))
        Next s

        dc.Save(outFile)

        ' Open the results for demonstration purposes.
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(inpFile) With {.UseShellExecute = True})
        System.Diagnostics.Process.Start(New System.Diagnostics.ProcessStartInfo(outFile) With {.UseShellExecute = True})
    End Sub
End Module

Download


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



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

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