Compress PDF Files in C#

Knowing how to reduce PDF file size can save you from a number of different frustrating hold-ups—like trying to send a large file via email, only to get the annoying popup telling us the file is too large to send. This post provides two solutions in C# to make PDFs smaller.

Before start, you should download .NET PDF component and add the dll file as reference to your Visual Studio.

Reducing PDF file size by compressing content

Content compression involves removing all extra space characters, inserting a single repeat character to indicate a string of repeated characters and substituting smaller bit strings for frequently occurring characters.

//Creates a new PDF document
PdfDocument doc = new PdfDocument();
//Load file
//Disables the incremental update
doc.FileInfo.IncrementalUpdate = false;
//Sets the compression level to best
doc.CompressionLevel = PdfCompressionLevel.Best;
//Save file

Reducing PDF file size by shrinking all images

For PDF files that contain many images, compressing/changing the quality of them all can make a noticeable difference in making your PDF smaller.

//Creates a new PDF document
PdfDocument pdf = new PdfDocument();
//Load file
pdf.FileInfo.IncrementalUpdate = false;

foreach (PdfPageBase page in pdf.Pages)
    Image[] images = page.ExtractImages();
    if (images != null && images.Length > 0)
        for (int j = 0; j < images.Length; j++)
            Image image = images[j];
            PdfBitmap bp = new PdfBitmap(image);
            bp.Quality = 20; //Reduces the quality of the image
            page.ReplaceImage(j, bp);
//Save file

Convert HTML String to PDF using Free API in C#

Converting from HTML to PDF is not an easy task. There are some tools that can do this, but most of them costs thousands of dollars. This article provides a free solution with only few lines of C# code, using free Spire.PDF.

Free Spire.PDF is a community edition of the fully featured Spire.PDF for .NET. It allows you to create PDF documents directly from HTML pages in your ASP.NET and MVC Websites, Desktop Applications and Services.

You can use the free library in .NET 4.0 and later applications, in C# and VB.NET languages, on 32-bit and 64-bit Windows machines.


Using the code

PdfDocument pdf = new PdfDocument();
PdfPageSettings setting = new PdfPageSettings();
setting.Size = PdfPageSize.A4;

PdfHtmlLayoutFormat htmlLayoutFormat = new PdfHtmlLayoutFormat();
htmlLayoutFormat.IsWaiting = false;                    
string htmlCode = File.ReadAllText("HTML example.html");
Thread thread = new Thread(() =>
{ pdf.LoadFromHTML(htmlCode, false, setting, htmlLayoutFormat); });




How to Print PDF to XPS in C#/VB.NET

Windows 7 comes with a Microsoft XPS Document Writer (MXDW) printer which can be used to print any document to an XPS file. It is also included in later releases, such as Windows 10. This article will introduce how to programmatically connect MXDW and print a PDF file into a XPS file.

To use following code snippets to print PDF file, you need to install Spire.PDF via NuGet and add the dll files into .NET assemblies.

Code Snippets

using Spire.Pdf;
namespace PrintPdfToXps
    class Program
        static void Main(string[] args)
            //load a Pdf document
            PdfDocument doc = new PdfDocument();

            //specify printer 
            doc.PrintDocument.PrinterSettings.PrinterName = "Microsoft XPS Document Writer";
            //print Pdf to a file instead a port
            doc.PrintDocument.PrinterSettings.PrintToFile = true;
            doc.PrintDocument.PrinterSettings.PrintFileName = "PrintToXps.xps";

            //start printing process

How to Create a Signature Field in PDF in C#

A signature field enables the user to place his signature in a form. This field type allows instant validation from a customer through his digital signature, eliminating the need of paper work. To prepare a document for digital signing, add one or more digital signature fields (depending on how many signatures are needed). This article presents how to create signature fields in a PDF document using Spire.PDF in C#.

Adding Necessary Namespaces

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

Using the code

STEP 1. Create a PDF document, create a blank page.

PdfDocument pdfdoc = new PdfDocument();
PdfPageBase page = pdfdoc.Pages.Add();

STEP 2. Draw some text in PDF.

PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 10f);
PdfSolidBrush brush = new PdfSolidBrush(Color.Black);
string s1 = "Representative #1";
string s2 = "Representative #2";
SizeF size = font.MeasureString(s1);
int x = 180;
int y1 = 120, y2 = 180;
page.Canvas.DrawString(s1, font, brush, new PointF(x, y1));
page.Canvas.DrawString(s2, font, brush, new PointF(x, y2));

STEP 3. Draw two line shapes on PDF.

PdfPen pen = new PdfPen(Color.Black, 0.5f);
page.Canvas.DrawLine(pen, new PointF(x + size.Width + 2, y1 +size.Height+ 2), new PointF(x + size.Width + 126, y1 + size.Height + 2));
page.Canvas.DrawLine(pen, new PointF(x + size.Width + 2, y2 + size.Height + 2), new PointF(x + size.Width + 126, y2 + size.Height + 2));

STEP 4. Create two signature fields in PDF and set the properties respectively.

PdfSignatureField signaturefield1 = new PdfSignatureField(page, "Signature1");
signaturefield1.BorderWidth = 1.0f;
signaturefield1.BorderStyle = PdfBorderStyle.Solid;
signaturefield1.BorderColor = new PdfRGBColor(System.Drawing.Color.White);
signaturefield1.HighlightMode = PdfHighlightMode.Outline;
signaturefield1.Bounds = new RectangleF(x+size.Width+5, y1 - 50 + size.Height, 120, 50);

PdfSignatureField signaturefield2 = new PdfSignatureField(page, "Signature2");
signaturefield2.BorderWidth = 1.0f;
signaturefield2.BorderStyle = PdfBorderStyle.Solid;
signaturefield2.BorderColor = new PdfRGBColor(System.Drawing.Color.White);
signaturefield2.HighlightMode = PdfHighlightMode.Outline;
signaturefield2.Bounds = new RectangleF(x+size.Width+5, y2 - 50 + size.Height, 120, 50);


STEP 5. Save to file.

doc.SaveToFile("SignatureField.pdf", FileFormat.PDF);



How to Programmatically Mark up Text in an Existing PDF Document in C#

Users often face the situation that you may need to emphasize the most important information from all text on a PDF page. Highlight text is such a functionality which allow users to give prominence to key words or sentence. In this tip, I will introduce how to mark up text in an existing PDF document programmatically in C#.

This scenario depends on .NET PDF component.  Please download it and add Spire.Pdf.dll as reference in your project. Following code snippets demonstrate how to accomplish this task using the classes provided by this component.

Step 1: Load the sample PDF document.

PdfDocument doc = new PdfDocument();
PdfPageBase page = doc.Pages[0];

Step 2: Find the text (words or sentence) that you want to mark up.

PdfTextFind ptf = page.FindText("Highlight text").Finds[0];

Step 3: Create a Markup Annotation based on the text.

Font font = ptf.Font;
string markupText = "Higlight text";
PdfTextMarkupAnnotation annotation = new PdfTextMarkupAnnotation("Adminstrator", "Text Markup Annotation", markupText, ptf.Position, new PdfTrueTypeFont(font));
annotation.Border = new PdfAnnotationBorder(0.75f);
annotation.TextMarkupColor = Color.Yellow;

Step 4: Add the annotation to PDF page.

doc.SaveToFile("Markup.pdf", FileFormat.PDF);

 Screenshot of Result