Сжатие PDF документа используя C#, VB.NET

Категория: PDF.NET

12 июля 2024

VintaSoft PDF .NET Plug-in можно использовать для сжатия и оптимизации PDF документа. Также VintaSoft PDF .NET Plug-in можно использовать для удаления метаданных PDF документа. Уменьшение размера PDF файла может помочь уменьшить сетевой трафик при передаче PDF файлов и уменьшить место занимаемое PDF файлами в хранилище данных. Это особенно полезно в таких областях, как архивирование, отправка по электронной почте и использование PDF документов в веб-приложениях.

Для оптимизации или сжатия PDF документа VintaSoft PDF .NET Plug-in может выполнить следующие действия:

Упаковка PDF документа

PDF документ может содержать не используемые объекты. VintaSoft PDF .NET Plug-in может удалить не используемые ресурсы в PDF документе.
Также PDF документ может содержать историю изменения PDF документа. VintaSoft PDF .NET Plug-in может удалить историю изменения документа из PDF документа.
Также ресурсы PDF документа могут быть сжаты не оптимальными алгоритмами компрессии (None, LZW). VintaSoft PDF .NET Plug-in может выполнить сжатие ресурсов используя более эффективные алгоритмы компрессии.
Также PDF документ содержит не сжатую таблицу перекрестных ссылок, если PDF файл использует формат PDF 1.4 или более раннюю версию. VintaSoft PDF .NET Plug-in может сохранить PDF документ в формате PDF 1.5 или выше и использовать сжатую таблицу перекрестных ссылок.

Вот C# код, который демонстрирует, как помощью класса Vintasoft.Imaging.Pdf.Processing.PdfDocumentCompressorCommand определить и удалить не используемые ресурсы, выполнить оптимальное сжатие ресурсов и сохранить PDF документ в оптимальном формате:
/// <summary>
/// Packs the PDF document.
/// </summary>
/// <param name="inPdfFilename">The input PDF filename.</param>
/// <param name="outPdfFilename">The output PDF filename.</param>
public static void PackDocument(string inPdfFilename, string outPdfFilename)
{
    // create compressor with empty compression settings
    Vintasoft.Imaging.Pdf.Processing.PdfDocumentCompressorCommand compressor =
        Vintasoft.Imaging.Pdf.Processing.PdfDocumentCompressorCommand.CreateEmptyCompressor();

    // specify that compressor must use maximum Flate compression level (best compression)
    compressor.FlateCompressionLevel = 9;
    // specify that compressor must recompress all resource that uses None, LZW, Flate compression using Flate compression
    compressor.RecompressFlateCompression = true;
    compressor.UseFlateInsteadLzwCompression = true;
    compressor.UseFlateInsteadNoneCompression = true;

    // specify that compressor must remove incremental update info and unused objects
    compressor.PackDocument = true;

    // if version of PDF document is lower than 1.7
    if (GetPdfDocumentVersion(inPdfFilename) < 17)
    {
        // set output format to PDF 1.7
        compressor.DocumentPackFormat = Vintasoft.Imaging.Pdf.PdfFormat.Pdf_17;
    }

    // compress PDF document
    compressor.Compress(inPdfFilename, outPdfFilename);
}

/// <summary>
/// Returns the PDF document version.
/// </summary>
/// <param name="pdfFilename">The PDF filename.</param>
/// <returns>The version number in dual-digit format (10,11,12,13,14,15,16,17,20,...).</returns>
private static int GetPdfDocumentVersion(string pdfFilename)
{
    using (Vintasoft.Imaging.Pdf.PdfDocument document = new Vintasoft.Imaging.Pdf.PdfDocument(pdfFilename))
        return document.Format.VersionNumber;
}


Оптимизация шрифтов PDF документа

Некоторые глифы шрифтов могут не использоваться для рендеринга текста в PDF документе - VintaSoft PDF .NET Plug-in позволяет удалить не используемые глифы из шрифтов PDF документа.

Вот C# код, который демонстрирует, как оптимизировать шрифты в PDF документе с помощью класса Vintasoft.Imaging.Pdf.Processing.PdfDocumentCompressorCommand:
/// <summary>
/// Subsets fonts in PDF document.
/// </summary>
/// <param name="inPdfFilename">The input PDF filename.</param>
/// <param name="outPdfFilename">The output PDF filename.</param>
public static void SubsetFonts(string inPdfFilename, string outPdfFilename)
{
    // create compressor with empty compression settings
    Vintasoft.Imaging.Pdf.Processing.PdfDocumentCompressorCommand compressor =
       Vintasoft.Imaging.Pdf.Processing.PdfDocumentCompressorCommand.CreateEmptyCompressor();

    // specify that compressor must subset fonts in PDF document
    compressor.SubsetFonts = true;

    // compress PDF document
    compressor.Compress(inPdfFilename, outPdfFilename);
}


Сжатие изображений PDF документа

Многие PDF документы содержат изображения. VintaSoft PDF .NET Plug-in позволяет уменьшить разрешение и глубину цвета ресурсов изображений в PDF документе, чтобы уменьшить размер PDF файла.

Вот C# код, который демонстрирует, как уменьшить разрешение и глубину цвета ресурсов изображений в PDF документе с помощью класса Vintasoft.Imaging.Pdf.Processing.PdfDocumentCompressorCommand:
/// <summary>
/// Detects "read color depth" of PDF image resources and compress PDF document with intent to view in 150DPI.
/// </summary>
/// <param name="inPdfFilename">The input PDF filename.</param>
/// <param name="outPdfFilename">The output PDF filename.</param>
public static void CompressToViewIn150DPI(string inPdfFilename, string outPdfFilename)
{
    // create compressor that will compress PDF document using lossy compression algorithms
    Vintasoft.Imaging.Pdf.Processing.PdfDocumentCompressorCommand compressor =
       Vintasoft.Imaging.Pdf.Processing.PdfDocumentCompressorCommand.CreateLossyCompressor(150, false, false, false);

    // specify that compressor must use JPEG compression for color images
    compressor.ColorImagesCompression = Vintasoft.Imaging.Pdf.PdfCompression.Jpeg;
    // specify that compressor must set JPEG quality to 70
    compressor.ColorImagesCompressionSettings.JpegQuality = 70;

    // specify that compressor must detect if image is bitonal image and use optimal compression for bitonal image
    compressor.DetectBitonalImageResources = true;
    // specify that compressor must detect if image is black-white image and use optimal compression for black-white image
    compressor.DetectBlackWhiteImageResources = true;
    // specify that compressor must detect if image is grayscale image and use optimal compression for grayscale image
    compressor.DetectGrayscaleImageResources = true;

    // compress PDF document
    compressor.Compress(inPdfFilename, outPdfFilename);
}


Очистка контента PDF документа

PDF документ может содержать не используемые объекты, такие как: ресурсы, страницы, шрифты, изображения, имена, операторы контента. Также PDF документ может содержать дубликаты ресурсов (например копии изображений или копии шрифтов). VintaSoft PDF .NET Plug-in может определить и удалить не используемые объекты и дубликаты ресурсов в PDF документе.

Вот C# код, который демонстрирует, как удалить не используемые объекты и дубликаты объектов из PDF документа с помощью класса Vintasoft.Imaging.Pdf.Processing.PdfDocumentCompressorCommand:
/// <summary>
/// Removes unused and duplicated resources in the PDF document.
/// </summary>
/// <param name="inPdfFilename">The input PDF filename.</param>
/// <param name="outPdfFilename">The output PDF filename.</param>
public static void RemoveUnsusedResources(string inPdfFilename, string outPdfFilename)
{
    // create compressor with empty compression settings
    Vintasoft.Imaging.Pdf.Processing.PdfDocumentCompressorCommand compressor =
       Vintasoft.Imaging.Pdf.Processing.PdfDocumentCompressorCommand.CreateEmptyCompressor();

    // specify that compressor must remove duplicate resources from PDF document
    compressor.RemoveDuplicateResources = true;
    // specify that compressor must remove unused names resources from PDF document
    compressor.RemoveUnusedNamedResources = true;
    // specify that compressor must remove unused names from PDF document
    compressor.RemoveUnusedNames = true;
    // specify that compressor must remove unused pages from PDF document
    compressor.RemoveUnusedPages = true;
    // specify that compressor must remove invalid bookmarks from PDF document
    compressor.RemoveInvalidBookmarks = true;
    // specify that compressor must remove invalid links from PDF document
    compressor.RemoveInvalidLinks = true;

    // compress PDF document
    compressor.Compress(inPdfFilename, outPdfFilename);
}


Удаление метаданных и других элементов PDF документа

PDF документ может содержать объекты которые не влияют на отображение страницы PDF документа, такие как: метаданные, закладки, вложенные файлы, интерактивная форма, миниатюры страниц, структурное дерево, информация о документе. VintaSoft PDF .NET Plug-in позволяет удалить объекты из PDF документа, если объекты не нужны.

Вот C# код, который демонстрирует, как удалить объекты из PDF документа с помощью класса Vintasoft.Imaging.Pdf.Processing.PdfDocumentCompressorCommand:
/// <summary>
/// Removes metadata, bookmarks, document information, embedded files, embedded thumbnails, interactive form and structure tree of the PDF document.
/// </summary>
/// <param name="inPdfFilename">The input PDF filename.</param>
/// <param name="outPdfFilename">The output PDF filename.</param>
public static void RemoveObjects(string inPdfFilename, string outPdfFilename)
{
    // create compressor with empty compression settings
    Vintasoft.Imaging.Pdf.Processing.PdfDocumentCompressorCommand compressor =
       Vintasoft.Imaging.Pdf.Processing.PdfDocumentCompressorCommand.CreateEmptyCompressor();

    // specify that compressor must remove metadata from PDF document
    compressor.RemoveMetadata = true;
    // specify that compressor must remove bookmarks from PDF document
    compressor.RemoveBookmarks = true;
    // specify that compressor must remove document information from PDF document
    compressor.RemoveDocumentInformation = true;
    // specify that compressor must remove embedded files from PDF document
    compressor.RemoveEmbeddedFiles = true;
    // specify that compressor must remove embedded thumbnails from PDF document
    compressor.RemoveEmbeddedThumbnails = true;
    // specify that compressor must remove interactive form from PDF document
    compressor.RemoveInteractiveForm = true;
    // specify that compressor must remove structure tree from PDF document
    compressor.RemoveStructureTree = true;

    // compress PDF document
    compressor.Compress(inPdfFilename, outPdfFilename);
}


Удаление аннотаций PDF документа

VintaSoft PDF .NET Plug-in позволяет удалить аннотации с PDF страницы, если аннотации на PDF страницы больше не нужны. Также VintaSoft PDF .NET Plug-in позволяет конвертировать аннотации в графику (flatten), если аннотации должны быть отображены на PDF странице, но пользователь больше не должен взаимодействовать с аннотациями.

Вот C# код, который демонстрирует, как сконвертировать аннотации в графику (flatten) и удалить интерактивную форму PDF документа с помощью класса Vintasoft.Imaging.Pdf.Processing.PdfDocumentCompressorCommand:
/// <summary>
/// Flatten an annotations and remove intractive form of the PDF document.
/// </summary>
/// <param name="inPdfFilename">The input PDF filename.</param>
/// <param name="outPdfFilename">The output PDF filename.</param>
public static void FlattenAnnotations(string inPdfFilename, string outPdfFilename)
{
    // create compressor with empty compression settings
    Vintasoft.Imaging.Pdf.Processing.PdfDocumentCompressorCommand compressor =
       Vintasoft.Imaging.Pdf.Processing.PdfDocumentCompressorCommand.CreateEmptyCompressor();

    // specify that compressor must remove interactive form from PDF document
    compressor.RemoveInteractiveForm = true;
    // specify that compressor must flatten annotations in PDF document
    compressor.FlattenAnnotations = true;

    // compress PDF document
    compressor.Compress(inPdfFilename, outPdfFilename);
}