Tutorial on How to Convert Tiff to PDF Using C#

Converting TIFF to PDF using C# is a common requirement in .NET document processing workflows. Developers often need to transform scanned documents or multi-page TIFF files into PDF format for better compatibility, easier distribution, and standardized document management.

TIFF files are widely used in scanning and archiving systems, especially for storing multiple pages in a single file. However, they are not always ideal for sharing or cross-platform viewing, while PDF provides a more universal and consistent format.

With Spire.PDF for .NET, you can efficiently convert TIFF images to PDF using simple and reliable C# code. This article demonstrates how to perform TIFF to PDF conversion in .NET, including handling multi-page TIFF images, adjusting page layouts, and applying best practices for real-world applications.


1. Understanding the Task

TIFF (Tagged Image File Format) is a flexible image format that supports multiple pages within a single file. This makes it popular for:

  • Scanned documents: Multi-page contracts, invoices, and forms
  • Document archiving: Preserving document history in a single file
  • Medical imaging: Storing diagnostic images with multiple views
  • Fax transmissions: Traditional fax systems often use TIFF format

Converting TIFF to PDF offers several advantages:

  • Universal compatibility: PDF viewers are available on all platforms
  • Smaller file size: PDF compression can reduce storage requirements
  • Better distribution: PDF is the standard for document sharing
  • Enhanced security: PDF supports encryption and access controls

2. Convert TIFF to PDF Using Spire.PDF

This section provides step-by-step examples for converting TIFF images to PDF using Spire.PDF in C#.

Install Spire.PDF for .NET

First, install the library via NuGet Package Manager:

Install-Package FreeSpire.PDF

Or using the .NET CLI:

dotnet add package FreeSpire.PDF

You can also download the Spire.PDF for .NET package and add it to your project manually.

Convert a Single-Page TIFF to PDF

For single-page TIFF files, the simplest approach is to create a PDF page that matches the original image dimensions and draw the image directly onto it. This ensures the TIFF content fills the entire PDF page without unwanted margins or scaling issues.

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

// Load the TIFF image
PdfImage tiffImage = PdfImage.FromFile("Sample_Page.tiff");

// Create a new PDF document
PdfDocument pdf = new PdfDocument();

// Remove default page margins
pdf.PageSettings.Margins.All = 0;

// Get image dimensions
float width = tiffImage.PhysicalDimension.Width;
float height = tiffImage.PhysicalDimension.Height;

// Add a PDF page with the same size as the TIFF image
PdfPageBase page = pdf.Pages.Add(new SizeF(width, height));

// Draw the image to fully fill the page
page.Canvas.DrawImage(tiffImage, 0, 0, width, height);

// Save the PDF document
pdf.SaveToFile("Sample_Page.pdf");
pdf.Close();

Convert Single-Page TIFF to PDF

Key API calls:

  • PdfImage.FromFile: Loads the TIFF image into a PDF-compatible object
  • PageSettings.Margins.All: Removes default margins to allow full-page rendering
  • Pages.Add(SizeF): Creates a PDF page that matches the TIFF dimensions
  • Canvas.DrawImage: Draws the TIFF image to completely fill the page
  • SaveToFile: Saves the converted PDF file

This method preserves the original TIFF dimensions and ensures the output PDF displays the image cleanly across the full page.

For more image-to-PDF scenarios, see how to convert images to PDF in C#.

Convert Multi-Page TIFF to PDF

Multi-page TIFF files contain multiple frames, with each frame representing a separate page. During conversion, you can iterate through each frame and create a PDF page that matches the dimensions of the current TIFF frame to preserve the original layout.

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
using System.Drawing.Imaging;

// Load the multi-page TIFF file
Image tiffImage = Image.FromFile("Sample89.tiff");

// Get frame information
FrameDimension dimension = new FrameDimension(tiffImage.FrameDimensionsList[0]);
int frameCount = tiffImage.GetFrameCount(dimension);

// Create a new PDF document
PdfDocument pdf = new PdfDocument();

// Remove default margins
pdf.PageSettings.Margins.All = 0;

// Process each TIFF frame
for (int i = 0; i < frameCount; i++)
{
    // Select current frame
    tiffImage.SelectActiveFrame(dimension, i);

    // Convert current frame to PdfImage
    PdfImage pdfImage = PdfImage.FromImage(tiffImage);

    // Get current frame dimensions
    float width = pdfImage.PhysicalDimension.Width;
    float height = pdfImage.PhysicalDimension.Height;

    // Create a PDF page matching the frame size
    PdfPageBase page = pdf.Pages.Add(new SizeF(width, height));

    // Draw the frame to fill the page
    page.Canvas.DrawImage(pdfImage, 0, 0, width, height);
}

// Save the PDF document
pdf.SaveToFile("Sample89.pdf");
pdf.Close();

// Release resources
tiffImage.Dispose();

Convert Multi-Page TIFF to PDF

Key concepts:

  • FrameDimension: Identifies the frame collection in a multi-page TIFF file
  • GetFrameCount: Retrieves the total number of TIFF pages
  • SelectActiveFrame: Switches to a specific TIFF frame for processing
  • Pages.Add(SizeF): Creates a PDF page that matches each TIFF page size
  • Canvas.DrawImage: Renders each TIFF frame onto the corresponding PDF page

This approach preserves all pages in the original TIFF file while ensuring each page fully occupies the PDF canvas without extra margins or scaling issues.

Fit TIFF Images into Standard PDF Pages

In some workflows, the output PDF must follow a standard page size such as A4 or Letter for printing, document sharing, or archival purposes. Instead of creating a PDF page based on the original TIFF dimensions, you can scale the image proportionally to fit within a fixed page size while keeping it horizontally centered.

using Spire.Pdf;
using Spire.Pdf.Graphics;

PdfDocument pdf = new PdfDocument();
PdfImage image = PdfImage.FromFile("Sample_Page.tiff");

// Create an A4 page with margins
PdfPageBase page = pdf.Pages.Add(PdfPageSize.A4, new PdfMargins(20));

// Calculate proportional scaling
float scale = Math.Min(
    page.Canvas.ClientSize.Width / image.PhysicalDimension.Width,
    page.Canvas.ClientSize.Height / image.PhysicalDimension.Height
);

// Calculate final image size
float width = image.PhysicalDimension.Width * scale;
float height = image.PhysicalDimension.Height * scale;

// Center horizontally and align to the top
float x = (page.Canvas.ClientSize.Width - width) / 2;

// Draw image onto the PDF page
page.Canvas.DrawImage(image, x, 0, width, height);

// Save the PDF file
pdf.SaveToFile("Sample89.pdf");
pdf.Close();

The Generated PDF will fit the standard page size while maintaining the original image dimensions.

Fit TIFF Images into Standard PDF Pages

Why use this approach?

  • Standardized output: Ensures all converted PDFs use consistent page sizes such as A4 or Letter
  • Better for printing: Prevents unusually sized PDF pages caused by large TIFF dimensions
  • Maintains aspect ratio: Scales the image proportionally without distortion
  • Cleaner document formatting: Keeps content properly aligned for business and archival workflows

This method works well when you need TIFF files to fit standardized PDF layouts rather than preserving their original dimensions.

You can also explore more PDF layout and page settings tutorials using C#.


3. Advanced TIFF to PDF Conversion Scenarios

For production applications, you often need additional control over the conversion process.

Batch Convert Multiple TIFF Files

In document management systems, scanned archives, or automated workflows, you may need to convert multiple TIFF files into PDF format at once. The following example processes all TIFF files in a folder and converts each file into a separate PDF while preserving the original image dimensions.

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
using System.IO;

string inputFolder = @"C:\Documents\TIFF";
string outputFolder = @"C:\Documents\PDF";

// Create the output folder if it doesn't exist
Directory.CreateDirectory(outputFolder);

// Process all TIFF files in the folder
foreach (string tiffFile in Directory.GetFiles(inputFolder, "*.tiff"))
{
    PdfImage image = PdfImage.FromFile(tiffFile);

    using (PdfDocument pdf = new PdfDocument())
    {
        // Create a PDF page matching the TIFF dimensions
        PdfPageBase page = pdf.Pages.Add(
            new SizeF(
                image.PhysicalDimension.Width,
                image.PhysicalDimension.Height
            )
        );

        // Draw the TIFF image onto the page
        page.Canvas.DrawImage(
            image,
            0,
            0,
            image.PhysicalDimension.Width,
            image.PhysicalDimension.Height
        );

        // Generate output file path
        string outputFile = Path.Combine(
            outputFolder,
            Path.GetFileNameWithoutExtension(tiffFile) + ".pdf"
        );

        // Save PDF
        pdf.SaveToFile(outputFile);
    }
}

Why use batch conversion?

  • Automatically processes large numbers of TIFF files
  • Reduces manual conversion work
  • Preserves original image dimensions for each file
  • Useful for archive migration and document automation workflows

This method works well for converting large collections of single-page TIFF files. If your folder contains multi-page TIFF documents, you can combine this approach with the multi-page conversion logic introduced earlier.

Merge Multiple TIFF Files into One PDF

If you need to combine several TIFF images into a single PDF document, you can add each TIFF file as a separate PDF page. This is useful when consolidating scanned documents, invoices, or image-based reports into one file.

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

string[] tiffFiles =
{
    "Page1.tiff",
    "Page2.tiff",
    "Page3.tiff"
};

PdfDocument pdf = new PdfDocument();

foreach (string file in tiffFiles)
{
    PdfImage image = PdfImage.FromFile(file);

    float width = image.PhysicalDimension.Width;
    float height = image.PhysicalDimension.Height;

    // Create page matching TIFF dimensions
    PdfPageBase page = pdf.Pages.Add(new SizeF(width, height));

    // Draw TIFF image
    page.Canvas.DrawImage(image, 0, 0, width, height);
}

// Save merged PDF
pdf.SaveToFile("CombinedDocument.pdf");
pdf.Close();

Benefits of merging TIFF files:

  • Combine multiple scanned pages into one PDF
  • Simplify document sharing
  • Preserve original image quality
  • Useful for contracts, invoices, and archived records

This method works best when each TIFF file should appear as an individual page in a single PDF document.

If you need to combine multiple converted PDF files into one document, you can also check how to merge PDF files in C#.

Handle Large TIFF Files Efficiently

Large multi-page TIFF files can consume significant memory during conversion. To improve performance, process each frame sequentially and release resources immediately after use.

using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;
using System.Drawing.Imaging;

// Process large TIFF files efficiently
using (Image tiffImage = Image.FromFile("LargeDocument.tiff"))
using (PdfDocument pdf = new PdfDocument())
{
    FrameDimension dimension =
        new FrameDimension(tiffImage.FrameDimensionsList[0]);

    int frameCount = tiffImage.GetFrameCount(dimension);

    for (int i = 0; i < frameCount; i++)
    {
        // Activate current frame
        tiffImage.SelectActiveFrame(dimension, i);

        using (PdfImage image = PdfImage.FromImage(tiffImage))
        {
            float width = image.PhysicalDimension.Width;
            float height = image.PhysicalDimension.Height;

            // Create page matching frame size
            PdfPageBase page = pdf.Pages.Add(
                new SizeF(width, height)
            );

            // Draw current frame
            page.Canvas.DrawImage(
                image,
                0,
                0,
                width,
                height
            );
        }
    }

    pdf.SaveToFile("LargeDocument.pdf");
}

Memory optimization tips:

  • Use using statements to automatically release resources
  • Process TIFF frames one at a time
  • Avoid loading multiple large images simultaneously
  • Improve performance when converting high-resolution scanned documents

This approach is particularly useful for large archival TIFF files, medical scans, and enterprise document migration tasks.


4. Common Issues and Solutions

When converting TIFF to PDF, developers may encounter the following issues.

Multi-Page TIFF Not Fully Converted

Symptoms: Only the first page appears in the PDF output.

Cause: Frames in the TIFF file are not properly iterated.

Solution: Use GetFrameCount and SelectActiveFrame to process each frame.

int frameCount = tiffImage.GetFrameCount(dimension);

for (int i = 0; i < frameCount; i++)
{
    tiffImage.SelectActiveFrame(dimension, i);
    // Process each frame
}

Image Distortion or Layout Issues

Symptoms: Image appears stretched or does not fit properly in the PDF page.

Cause: Incorrect scaling when fitting TIFF into a fixed-size page (e.g., A4).

Solution: Use proportional scaling while keeping aspect ratio.

float scale = Math.Min(
    page.Canvas.ClientSize.Width / image.PhysicalDimension.Width,
    page.Canvas.ClientSize.Height / image.PhysicalDimension.Height
);

float width = image.PhysicalDimension.Width * scale;
float height = image.PhysicalDimension.Height * scale;

High Memory Usage with Large Files

Symptoms: Slow performance or memory issues when processing large TIFF files.

Cause: Loading multi-page TIFF into memory without proper disposal.

Solution: Process frames sequentially and release resources promptly.

using (Image tiffImage = Image.FromFile("Large.tiff"))
using (PdfDocument pdf = new PdfDocument())
{
    // Process frames one by one
}

Unsupported TIFF Format

Symptoms: Errors occur when loading certain TIFF files.

Cause: Non-standard compression or color formats in the TIFF file.

Solution: Ensure the TIFF uses standard formats supported by the library.


Conclusion

Converting TIFF to PDF in C# is a straightforward process with Spire.PDF for .NET. The library provides efficient methods for handling both single-page and multi-page TIFF files while maintaining image quality and layout accuracy.

By following the examples and best practices demonstrated in this article, developers can implement reliable TIFF to PDF conversion for various scenarios including document archiving, batch processing, and enterprise document management systems.

If you want to evaluate the functionality of Spire.PDF for .NET, you can apply for a free trial license.


FAQ

How do I convert a multi-page TIFF to PDF in C#?

Use FrameDimension to access each frame in the TIFF file, then create a separate PDF page for each frame. The GetFrameCount method returns the total number of frames, and SelectActiveFrame allows you to process each frame individually.

What is the best approach for converting TIFF to PDF in .NET?

Using a dedicated library like Spire.PDF for .NET provides the most reliable and efficient solution. It handles image loading and PDF generation with minimal code while supporting multi-page TIFF files.

Does converting TIFF to PDF reduce file size?

PDF compression can reduce file size compared to uncompressed TIFF files. However, the actual size reduction depends on the original TIFF compression, image content, and PDF settings. High-resolution images may still result in large PDF files.

Can I convert TIFF to PDF without installing Microsoft Office or additional software?

Yes. Spire.PDF for .NET operates independently and does not require Microsoft Office, Adobe Acrobat, or any other external software. It performs all conversion operations using its own rendering engine.

How can I maintain image quality when converting TIFF to PDF?

To preserve image quality, avoid unnecessary scaling and match PDF page dimensions to the TIFF image size for best results.

Monday, 30 June 2014 06:59

Remove Table from PowerPoint document

Spire.Presentation is a powerful and easy-to-use .NET component, especially designed for developers. Using Spire.Presentation you can generate, modify, convert, render, and print documents without installing Microsoft PowerPoint on your machine. There is a document in our website introducing you how to insert table. And in this document, I will introduce you how to remove tables within a PPT document.

Step 1: Create Presentation instance and load file.

Presentation presentation = new Presentation();
presentation.LoadFromFile("sample.ppt");

Step 2: Get the tables within the PPT document.

 List<IShape> shape_tems = new List<IShape>();
foreach (IShape shape in presentation.Slides[0].Shapes)
{
    if (shape is ITable)
    {
        //add new table to table list
        shape_tems.Add(shape);
    }
}

Step 3: Remove all tables.

foreach (IShape shape in shape_tems)
{
    presentation.Slides[0].Shapes.Remove(shape);
}

Step 4: Save the document.

presentation.SaveToFile("result.pptx", FileFormat.Pptx2010);

Download and install Spire.Presentation for .NET and refer to below code to remove tables within PPT document.

Screenshots:

Before:

Remove Table from PowerPoint document

After:

Remove Table from PowerPoint document

Full Code:

[C#]
//create Presentation instance and load file
Presentation presentation = new Presentation();
presentation.LoadFromFile("sample.ppt");

//get the tables in PowerPoint document
List<IShape> shape_tems = new List<IShape>();
foreach (IShape shape in presentation.Slides[0].Shapes)
{
    if (shape is ITable)
    {
        //add new table to table list
        shape_tems.Add(shape);
    }
}

//remove all tables
foreach (IShape shape in shape_tems)
{
    presentation.Slides[0].Shapes.Remove(shape);
}

//save the document
presentation.SaveToFile("result.pptx", FileFormat.Pptx2010);
System.Diagnostics.Process.Start("result.pptx");
[VB.NET]
'create Presentation instance and load file
Dim presentation As New Presentation()
presentation.LoadFromFile("sample.ppt")

'get the tables in PowerPoint document
Dim shape_tems As New List(Of IShape)()
For Each shape As IShape In presentation.Slides(0).Shapes
    If TypeOf shape Is ITable Then
        'add new table to table list
        shape_tems.Add(shape)
    End If
Next

'remove all tables
For Each shape As IShape In shape_tems
    presentation.Slides(0).Shapes.Remove(shape)
Next

'save the document
presentation.SaveToFile("result.pptx", FileFormat.Pptx2010)
System.Diagnostics.Process.Start("result.pptx")

If you couldn't successfully use Spire.Presentation, please refer Spire.Presentation Quick Start which can guide you quickly use Spire.Presentation.

Thursday, 19 June 2014 01:50

MailMerge

Agreement Start Date:
Agreement End Date:
Agreement Extension Date:
Documentation Start Date:
Documentation End Date:
downloads
  • Demo
  • Java
  • C# source
This demo shows you how to merge some data into a Word template. Our Spire.Doc provides also the function NestedMailMerge with which you can merge the main-table and sub-table into a Word template to get a professional report. You can get a full demo from the article How to Use Mail Merge to Create Report
import com.spire.doc.Document;
import com.spire.doc.FileFormat;

import java.text.SimpleDateFormat;
import java.util.ArrayList;

public class MailMargeDemo {

     public void mailMerge(String docFile, String resultFilePath) throws Exception {
        Document doc = new Document();
        doc.loadFromFile(docFile);

        SimpleDateFormat format=new SimpleDateFormat("yyyy-MM-dd");
        Calendar calendar=Calendar.getInstance();

        ArrayList dateList=new ArrayList<>();
        int []offset={-5,5,6,-2,2};
        for(int data:offset){
            calendar.setTime(new Date());
            calendar.add(Calendar.YEAR,data);
            dateList.add(format.format(calendar.getTime()));
        }
        String[] values =new String[dateList.size()];
        dateList.toArray(values);
        
        String []fields={
                "SubGrantPAStartDateValue",
                "SubGrantPAEndDateValue",
                "SubGrantPAExtensionDateValue",
                "SubGrantPSStartDateValue",
                "SubGrantPSEndDateValue"
        };
        doc.getMailMerge().execute(fields,values);
        doc.saveToFile(resultFilePath, FileFormat.Docx);
    }
}
No Matter How Big or Small Your Project is,
Any technical question related to our product, contact us at support@e-iceblue.com.
Any question related to the purchase of product, contact us at sales@e-iceblue.com.
If you don't find the function you want, please request a free demo from us.
Thursday, 19 June 2014 01:48

Table

Data

Name Capital Continent Area Population Flag
Argentina Buenos Aires South America 2777815 32300003
Bolivia La Paz South America 1098575 7300000
Brazil Brasilia South America 8511196 150400000
Canada Ottawa North America 9976147 26500000
Chile Santiago South America 756943 13200000
Colombia Bagota South America 1138907 33000000
Cuba Havana North America 114524 10600000
Ecuador Quito South America 455502 10600000
El Salvador San Salvador North America 20865 5300000
Guyana Georgetown South America 214969 800000

Option

Header Back Color:
Row Back Color:
Alternation Back Color:
Border Color:
downloads
  • Demo
  • Java
  • C# source
This demo shows you how to create a table with specified data in a Word document. We also show you how to set the border and background color of the table.
No Matter How Big or Small Your Project is,
Any technical question related to our product, contact us at support@e-iceblue.com.
Any question related to the purchase of product, contact us at sales@e-iceblue.com.
If you don't find the function you want, please request a free demo from us.
Thursday, 19 June 2014 01:42

HeaderAndFooter

Thursday, 19 June 2014 01:36

FindAndHighlight

Upload

Maximum file size: 1 MB. Files accepted: doc, docx, txt, rtf.
Click here to browse files.
fileerrors

Convert to

Source file:
filename
Search Text:
  • Demo
  • Java
  • C# source
This demo shows you how to search text in a Word document and highlight the text matched.
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
import com.spire.doc.documents.TextSelection;

import java.awt.*;


public class FindHighlightDemo {
    public void findHeighlight(String docFile, String findText, String resultFilePath){
        Document doc = new Document();
        doc.loadFromFile(docFile);
        TextSelection[] textSelections = doc.findAllString(findText, false, true);
		if(textSelections!=null){
			for (TextSelection selection : textSelections) {
				selection.getAsOneRange().getCharacterFormat().setHighlightColor(Color.YELLOW);
			}
		}
        doc.saveToFile(resultFilePath, FileFormat.Docx);
    }
}
No Matter How Big or Small Your Project is,
Any technical question related to our product, contact us at support@e-iceblue.com.
Any question related to the purchase of product, contact us at sales@e-iceblue.com.
If you don't find the function you want, please request a free demo from us.
Thursday, 19 June 2014 01:33

Conversion

Upload

Maximum file size: 1 MB. Files accepted: doc, docx, txt, rtf.
Click here to browse files.
fileerrors

Convert to

Source file:
filename
Target file type:
  • Demo
  • Java
  • C# source
This demo shows you how to convert a Word document (doc/docx) to PDF, HTML, Image, XPS, RTF and other file format.
No Matter How Big or Small Your Project is,
Any technical question related to our product, contact us at support@e-iceblue.com.
Any question related to the purchase of product, contact us at sales@e-iceblue.com.
If you don't find the function you want, please request a free demo from us.

Blank pages in PDFs are not uncommon to find because they may have been left intentionally by the author or added accidentally when manipulating documents. These blank pages can be annoying when you are reading or printing the document, so it may be quite necessary to remove them. In this article you will learn how to programmatically find and remove blank pages from PDF documents using Spire.PDF for .NET.

Install Spire.PDF for .NET

To begin with, you need to add the DLL files included in the Spire.PDF for.NET package as references in your .NET project. The DLLs files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Find and Delete Blank Pages from a PDF Document

Spire.PDF for .NET provides a method PdfPageBase.IsBlank() to detect if a PDF page is absolutely blank. But some pages that look blank actually contain white images, these pages won't be deemed as blank using the PdfPageBase.IsBlank() method. Therefore, it is necessary to create a custom method IsImageBlank() to be used in conjunction with PdfPageBase.IsBlank() method to detect these white but non-blank pages.

Note: This solution will convert PDF pages into images and detect if an image is blank. It is necessary to apply a license to remove the evaluation message in the converted images. Otherwise, this method won't work properly. If you do not have a license, contact sales@e-iceblue.com for a temporary one for evaluation purpose.

The detailed steps are as follows:

  • Create a PdfDocument instance.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Loop through the pages in the PDF document to detect if the pages are blank using PdfPageBase.IsBlank() method.
  • For absolutely blank pages, delete them using PdfDocument.Pages.RemoveAt() method.
  • For pages that are not absolutely blank, save them as images using PdfDocument.SaveAsImage() method. Then detect if the converted images are blank using custom method IsImageBlank() and remove the pages that are "blank" using PdfDocument.Pages.RemoveAt() method.
  • Save the result document using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace DeleteBlankPage
{
    class Program
    {
        static void Main(string[] args)
        {
            //Apply license by license key
            Spire.Pdf.License.LicenseProvider.SetLicenseKey("your license key");

            //Create a PdfDocument instance
            PdfDocument document = new PdfDocument();

            //Load a sample PDF document
            document.LoadFromFile("input.pdf");

            //Loop through all pages in the PDF
            for (int i = document.Pages.Count - 1; i >= 0; i--)
            {
                //Detect if a page is blank
                if (document.Pages[i].IsBlank())
                {
                    //Remove the absolutely blank page
                    document.Pages.RemoveAt(i);
                }
                else
                {
                    //Save PDF page as image
                    Image image = document.SaveAsImage(i, PdfImageType.Bitmap);

                    //Detect if the converted image is blank
                    if (IsImageBlank(image))
                    {
                        //Remove the page
                        document.Pages.RemoveAt(i);
                    }
                }
            }

            //Save the result document
            document.SaveToFile("RemoveBlankPage.pdf", FileFormat.PDF);
        }

        //Detect if an image is blank
        public static bool IsImageBlank(Image image)
        {
            Bitmap bitmap = new Bitmap(image);
            for (int i = 0; i < bitmap.Width; i++)
            {
                for (int j = 0; j < bitmap.Height; j++)
                {
                    Color pixel = bitmap.GetPixel(i, j);
                    if (pixel.R < 240 || pixel.G < 240 || pixel.B < 240)
                    {
                        return false;
                    }
                }
            }
            return true;
        }
    }
}

C#/VB.NET: Find and Remove Blank Pages from PDF

Apply for a Temporary License

If you'd like to remove the evaluation message from the generated documents, or to get rid of the function limitations, please request a 30-day trial license for yourself.

Tuesday, 27 May 2014 08:40

Delete Annotation from PDF files in C#

Text annotation is often used in PDF file to show readers the extra information of the item. By using Spire.PDF you can not only add a new annotation, edit an existing annotation, but also delete annotations from PDF file. In this article, we will introduce you how to delete a particular annotation and delete all the annotation at one time.

First, check the PDF document with annotations.

Delete Annotation from PDF files in C#

Here comes to the steps of how to remove the bookmarks in C#.

  • Download Spire.PDF for .NET and install it correctly. The Spire.PDF installation is clean, professional and wrapped up in a MSI installer.
  • Add Spire.Pdf.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Pdf\Bin\NET4.0\ Spire.Pdf.dll".
  • Check the code snippet of how to delete the annotations. With Spire.PDF.NET, we can remove both the particular annotation and remove all the annotations.

The code snippet of remove the first annotation from PDF file:

//Example 1: Remove the first annotation from the PDF file
PdfDocument document = new PdfDocument();
//load the pdf file
document.LoadFromFile("E-iceblue.pdf");

//remove the first annotation
PdfAnnotationCollection.Create(document.Pages[0]).RemoveAt(1);

document.SaveToFile("result.pdf");
System.Diagnostics.Process.Start("result.pdf");

The effective screenshot of remove the first annotation:

Delete Annotation from PDF files in C#

The code snippet of remove all annotations from PDF file:

//Example 2: Remove all annotations from the PDF file
PdfDocument document = new PdfDocument();
//load the pdf file
document.LoadFromFile("E-iceblue.pdf");

//remove all annotations
PdfAnnotationCollection.Create(document.Pages[0]).Clear();

document.SaveToFile("result.pdf");
System.Diagnostics.Process.Start("result.pdf");

The effective screenshot of remove all the annotations:

Delete Annotation from PDF files in C#

Suppose you want your doc document more attract and prominent your content. You would use a kind of border and shading style to beatify your document and give prominence to the key points. AS well as doc document the PPT document also can set shape to as border and shading.

Spire.Presentation for .NET, a professional .NET PPT component to allow users to manipulate PPT documents without automation. It can set kinds of shape types which can help users to beatify their document as their expectation

Below demonstrate the effect by a screenshot which shows a shape type in PPT document with C#, VB.NET via Spire.Presentation for .NET.

Set border and shading in PPT document

There is a guide to introduce a method to set shape type to achieve above screenshot with C#, VB.NET via Spire.Presentation for .NET.

This method is:

First, new a PPT document and set its slide. Then, new a shape and set its line color and gradient color. Last set the font and fill style for the paragraph. Now Download and install Spire.Presentation for .NET and use below code to experience this method to set shape type in PPT document.

The full code:

[C#]
using System;
using System.Drawing;
using Spire.Presentation;
using Spire.Presentation.Drawing;

namespace BorderAndShading
{
    class Program
    {
        static void Main(string[] args)
        {
            Presentation presentation = new Presentation();

            //set background Image
            string ImageFile = @" bg.png";
            RectangleF rect = new RectangleF(0, 0, presentation.SlideSize.Size.Width, presentation.SlideSize.Size.Height);
            presentation.Slides[0].Shapes.AppendEmbedImage(ShapeType.Rectangle, ImageFile, rect);
            presentation.Slides[0].Shapes[0].Line.FillFormat.SolidFillColor.Color = Color.FloralWhite;

            //append new shape
            IAutoShape shape = presentation.Slides[0].Shapes.AppendShape(ShapeType.Rectangle,
                new RectangleF(120, 70, 450, 300));

            //set the LineColor
            shape.ShapeStyle.LineColor.Color = Color.Green;

            //set the gradient color of shape
            shape.Fill.FillType = Spire.Presentation.Drawing.FillFormatType.Gradient;
            shape.Fill.Gradient.GradientShape = Spire.Presentation.Drawing.GradientShapeType.Rectangle;
            shape.Fill.Gradient.GradientStyle = Spire.Presentation.Drawing.GradientStyle.FromTopLeftCorner;
            shape.Fill.Gradient.GradientStops.Append(1f, KnownColors.GreenYellow);
            shape.Fill.Gradient.GradientStops.Append(0, KnownColors.PowderBlue);
            shape.AppendTextFrame("Borders and Shading");

            //set the Font
            shape.TextFrame.Paragraphs[0].TextRanges[0].LatinFont = new TextFont("Arial Black");
            shape.TextFrame.Paragraphs[0].TextRanges[0].Fill.FillType = FillFormatType.Solid;
            shape.TextFrame.Paragraphs[0].TextRanges[0].Fill.SolidColor.Color = Color.Black;

            //save the document
            presentation.SaveToFile("BordersAndShading.pptx", FileFormat.Pptx2007);
            System.Diagnostics.Process.Start("BordersAndShading.pptx");
        }
    }
}
[VB.NET]
Imports System.Text
Imports System.Drawing
Imports Spire.Presentation
Imports Spire.Presentation.Drawing

Module Module1

    Sub Main()
        'create PPT document
        Dim presentation As New Presentation()

        'set background Image
        Dim ImageFile As String = "bg.png"
        Dim rect As New RectangleF(0, 0, presentation.SlideSize.Size.Width, presentation.SlideSize.Size.Height)
        presentation.Slides(0).Shapes.AppendEmbedImage(ShapeType.Rectangle, ImageFile, rect)
        presentation.Slides(0).Shapes(0).Line.FillFormat.SolidFillColor.Color = Color.FloralWhite

        'append new shape
        Dim shape As IAutoShape = presentation.Slides(0).Shapes.AppendShape(ShapeType.Rectangle, New RectangleF(30, 70, 550, 300))

        'set the LineColor
        shape.ShapeStyle.LineColor.Color = Color.Green

        'set the gradient color of shape
        shape.Fill.FillType = Spire.Presentation.Drawing.FillFormatType.Gradient
        shape.Fill.Gradient.GradientShape = Spire.Presentation.Drawing.GradientShapeType.Rectangle
        shape.Fill.Gradient.GradientStyle = Spire.Presentation.Drawing.GradientStyle.FromTopLeftCorner
        shape.Fill.Gradient.GradientStops.Append(1.0F, KnownColors.GreenYellow)

        shape.Fill.Gradient.GradientStops.Append(0, KnownColors.PowderBlue)
        shape.AppendTextFrame("Borders and Shading")

        'set the Font
        shape.TextFrame.Paragraphs(0).TextRanges(0).LatinFont = New TextFont("Arial Black")
        shape.TextFrame.Paragraphs(0).TextRanges(0).Fill.FillType = FillFormatType.Solid
        shape.TextFrame.Paragraphs(0).TextRanges(0).Fill.SolidColor.Color = Color.Black

        'save the document
        presentation.SaveToFile("BordersAndShading.pptx", FileFormat.Pptx2007)
        System.Diagnostics.Process.Start("BordersAndShading.pptx")

    End Sub

End Module