C#/VB.NET: Create a Multi-Column PDF

2023-01-05 02:26:00 Written by Koohji

When designing magazines or newspapers, you may need to display content in multiple columns on a single page to improve readability. In this article, you will learn how to programmatically create a two-column PDF from scratch 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

Create a Two-Column PDF from Scratch in C# and VB.NET

Spire.PDF for .NET allows you to create a two-column PDF by drawing text at two separate rectangle areas in a PDF page. Below are the detailed steps to achieve the task.

  • Create a PdfDocument instance.
  • Add a new page in the PDF using PdfDocument.Pages.Add() method.
  • Define paragraph text, then set the text font and text alignment.
  • Draw text at two separate rectangle areas in the PDF using PdfPageBase.Canvas.DrawString (String, PdfFontBase, PdfBrush, RectangleF, PdfStringFormat) method.
  • Save the result file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace CreateTwoColumnPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument doc = new PdfDocument();

            //Add a new page
            PdfPageBase page = doc.Pages.Add();

            //Define paragraph text
            string s1 = "Spire.PDF for .NET is a professional PDF component applied to creating, writing, "
                        + "editing, handling and reading PDF files without any external dependencies within "
                        + ".NET application. Using this .NET PDF library, you can implement rich capabilities "
                        + "to create PDF files from scratch or process existing PDF documents entirely through "
                        + "C#/VB.NET without installing Adobe Acrobat.";

            string s2 = "Many rich features can be supported by the .NET PDF API, such as security setting "
                        + "(including digital signature), PDF text/ attachment/ image extract, PDF merge/ split "
                        + ", metadata update, section, graph/ image drawing and inserting, table creation and "
                        + "processing, and importing data etc.Besides, Spire.PDF for .NET can be applied to easily "
                        + "converting Text, Image and HTML to PDF with C#/VB.NET in high quality.";

            //Get width and height of page
            float pageWidth = page.GetClientSize().Width;
            float pageHeight = page.GetClientSize().Height;

            //Create a PdfSolidBrush instance
            PdfSolidBrush brush = new PdfSolidBrush(new PdfRGBColor(Color.Black));

            //Create a PdfFont instance
            PdfFont font = new PdfFont(PdfFontFamily.TimesRoman, 14f);

            //Set the text alignment via PdfStringFormat class
            PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Left);

            //Draw text
            page.Canvas.DrawString(s1, font, brush, new RectangleF(0, 20, pageWidth / 2 - 8f, pageHeight),format);
            page.Canvas.DrawString(s2, font, brush, new RectangleF(pageWidth / 2 + 8f, 20, pageWidth / 2, pageHeight), format);

            //Save the result document
            doc.SaveToFile("CreateTwoColumnPDF.pdf.pdf");
        }
    }
}

C#/VB.NET: Create a Multi-Column 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.

When we operate the Microsoft PowerPoint documents, we can set whether to show some additional information of slides to readers, such as “Date and Time”, “Slide number” and footer. This article will demonstrate how to set whether to show these information to readers in C# with the help of Spire.Presentation.

Firstly, view the screenshot of the property of slide appearance on the header and footer area.

Whether to display the additional information for presentation slides on header and footer area

Step 1: Create a presentation instance and load the document from file.

Presentation ppt = new Presentation();
ppt.LoadFromFile("Sample.pptx", FileFormat.Pptx2010);

Step 2: Set the appearance property for slide number, footer and date time.

ppt.SlideNumberVisible = true;

ppt.FooterVisible = false;

ppt.DateTimeVisible = false;

Step 3: Save the document to file.

ppt.SaveToFile("Result.pptx", FileFormat.Pptx2010);

Effective screenshot of the slide appearance on header and footer area.

Whether to display the additional information for presentation slides on header and footer area

Full codes of how to set the additional information of presentation slides’ header and footer area:

using Spire.Presentation;
using Spire.Xls;
namespace AdditionalInfo
{

    class Program
    {

        static void Main(string[] args)
        {
            Presentation ppt = new Presentation();
            ppt.LoadFromFile("Sample.pptx", FileFormat.Pptx2010);

            ppt.SlideNumberVisible = true;

            ppt.FooterVisible = false;

            ppt.DateTimeVisible = false;

            ppt.SaveToFile("Result.pptx", FileFormat.Pptx2010);

        }
    }
}

PDF actions can refer to external files by using either absolute or relative file paths. While using the relative path in action, the file can be moved into a different location. In Spire.PDF, we can use the PdfLaunchAction to link to files with relative paths.

Code snippet:

Step 1: Create a new PDF document and add a page to it.

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

Step 2: Create a PDF launch action that refers to an external file with relative path.

PdfLaunchAction launchAction = new PdfLaunchAction(@"..\..\test.txt", PdfFilePathType.Relative);

Step 3: Create a PDF action annotation with the launch action. Add the annotation to the page.

string text = "Click here to open file with relative path";
PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 13f));
RectangleF rect = new RectangleF(50, 50, 230, 15);
page.Canvas.DrawString(text, font, PdfBrushes.ForestGreen, rect);
PdfActionAnnotation annotation = new PdfActionAnnotation(rect, launchAction);
(page as PdfNewPage).Annotations.Add(annotation);     

Step 4: Save the document.

document.SaveToFile("RelativeFilePath.pdf");

Screenshot:

Link to files with relative paths using PdfLaunchAction

Full code:

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

namespace Link_to_files_with_relative_paths
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a new PDF document and add a page to it
            PdfDocument document = new PdfDocument();
            PdfPageBase page = document.Pages.Add();

            //Create a PDF Launch Action       
            PdfLaunchAction launchAction = new PdfLaunchAction(@"..\..\test.txt", PdfFilePathType.Relative);
            
            //Create a PDF Action Annotation with the PDF Launch Action
            string text = "Click here to open file with relative path";
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 13f));
            RectangleF rect = new RectangleF(50, 50, 230, 15);
            page.Canvas.DrawString(text, font, PdfBrushes.ForestGreen, rect);
            PdfActionAnnotation annotation = new PdfActionAnnotation(rect, launchAction); 
             //Add the PDF Action Annotation to page
            (page as PdfNewPage).Annotations.Add(annotation);           

            //Save and close the document
            document.SaveToFile("RelativeFilePath.pdf");
            document.Close();
        }
    }
}

Spire.PDF provides support to render simple HTML string in a PDF document by using PdfHTMLTextElement class. (Only available on .NET, .Net Core/ .NET Standard doesn't offer PdfHTMLTextElement & PdfMetafileLayoutFormat class) This class supports a set of basic HTML tags including Font, B, I, U, Sub, Sup and BR. For complex HTML rendering with CSS, please check Convert HTML String to PDF.

Following code snippets demonstrates how we can insert HTML styled text to PDF.

Step 1: Create a new PDF document, add a page to it.

PdfDocument doc = new PdfDocument();
PdfNewPage page = doc.Pages.Add() as PdfNewPage;

Step 2: Define HTML string.

string htmlText= "This demo shows how we can insert <u><i>HTML styled text</i></u> to PDF using "
                 + "<font color='#FF4500'>Spire.PDF for .NET</font>. ";

Step 3: Render HTML text.

PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 5);
PdfBrush brush = PdfBrushes.Black;
PdfHTMLTextElement richTextElement = new PdfHTMLTextElement(htmlText, font, brush);
richTextElement.TextAlign = TextAlign.Left;

Step 4: Format page layout to enable that the HTML text will break into multiple pages if the content exceeds one page.

PdfMetafileLayoutFormat format = new PdfMetafileLayoutFormat();
format.Layout = PdfLayoutType.Paginate;
format.Break = PdfLayoutBreakType.FitPage;

Step 5: Draw HTML string on page.

richTextElement.Draw(page, new RectangleF(0, 20, page.GetClientSize().Width, page.GetClientSize().Height/2),format);

Step 6: Save the document.

doc.SaveToFile("Output.pdf");

Output:

How to Insert HTML Styled Text to PDF in C#, VB.NET

Full Code:

[C#]
using Spire.Pdf;
using Spire.Pdf.Graphics;
using System.Drawing;


namespace InsertHTMLStyledTexttoPDF
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a Pdf document
            PdfDocument doc = new PdfDocument();

            //Add a new page
            PdfNewPage page = doc.Pages.Add() as PdfNewPage;

            //HTML string
            string htmlText = "This demo shows how we can insert HTML styled text to PDF using "
                             + "Spire.PDF for .NET. ";

            //Render HTML text
            PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 5);
            PdfBrush brush = PdfBrushes.Black;
            PdfHTMLTextElement richTextElement = new PdfHTMLTextElement(htmlText, font, brush);
            richTextElement.TextAlign = TextAlign.Left;

            //Format Layout
            PdfMetafileLayoutFormat format = new PdfMetafileLayoutFormat();
            format.Layout = PdfLayoutType.Paginate;
            format.Break = PdfLayoutBreakType.FitPage;

            //Draw htmlString  
            richTextElement.Draw(page, new RectangleF(0, 20, page.GetClientSize().Width, page.GetClientSize().Height / 2), format);
            doc.SaveToFile("Output.pdf");
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing


Namespace InsertHTMLStyledTexttoPDF
	Class Program
		Private Shared Sub Main(args As String())
			'Create a Pdf document
			Dim doc As New PdfDocument()

			'Add a new page
			Dim page As PdfNewPage = TryCast(doc.Pages.Add(), PdfNewPage)

			'HTML string
			Dim htmlText As String = "This demo shows how we can insert HTML styled text to PDF using " + "Spire.PDF for .NET. "

			'Render HTML text
			Dim font As New PdfFont(PdfFontFamily.Helvetica, 5)
			Dim brush As PdfBrush = PdfBrushes.Black
			Dim richTextElement As New PdfHTMLTextElement(htmlText, font, brush)
			richTextElement.TextAlign = TextAlign.Left

			'Format Layout
			Dim format As New PdfMetafileLayoutFormat()
			format.Layout = PdfLayoutType.Paginate
			format.Break = PdfLayoutBreakType.FitPage

			'Draw htmlString  
			richTextElement.Draw(page, New RectangleF(0, 20, page.GetClientSize().Width, page.GetClientSize().Height / 2), format)
			doc.SaveToFile("Output.pdf")
		End Sub
	End Class
End Namespace

C# code example to compress PDFs

PDF is one of the most popular formats for distributing, archiving, and presenting digital documents. However, when PDFs include high-resolution images, scanned pages, or embedded fonts, their file sizes can grow considerably. Large PDF files can slow down upload and download speeds, take up unnecessary storage space, and even cause issues with email attachments and website performance.

This complete guide shows you how to compress PDF documents in C# using the Spire.PDF for .NET library. It covers multiple compression strategies—image compression, font optimization, and content compression—with practical, ready-to-use C# code examples to help you streamline PDF size effectively in your .NET applications.

Table of Contents

Why Compress PDF Files?

Compressing PDF files can bring significant benefits, especially in professional and enterprise environments:

  • Faster upload and download speeds
  • Reduced storage consumption
  • Easier email sharing with smaller attachments
  • Improved performance in web-based PDF viewers
  • Better experience on mobile and low-bandwidth environments

Whether you're working with reports, invoices, or scanned documents, PDF compression ensures efficient document handling and delivery.

Install the Library for PDF Compression in .NET

Spire.PDF for .NET is a robust and developer-friendly library that enables developers to create, edit, convert, and compress PDF documents without relying on Adobe Acrobat. It supports various compression options to minimize PDF file sizes effectively.

PDF Compression Library for .NET

Installation Steps

You can easily install Spire.PDF for .NET via NuGet using one of the following methods:

Option 1: Using NuGet Package Manager

  1. Open your project in Visual Studio.
  2. Right-click on the project → Manage NuGet Packages.
  3. Search for Spire.PDF.
  4. Click Install.

Option 2: Using the Package Manager Console

Install-Package Spire.PDF

Once installed, you can start using the built-in compression APIs to optimize PDF file size.

How to Optimize PDF File Size in C# (Methods and Code Examples)

Spire.PDF provides multiple techniques to reduce PDF size. In this section, you'll learn how to implement three key methods: compressing images, optimizing fonts, and compressing overall document content.

Method 1. Compressing Images

High-resolution images embedded in PDF files often consume the most space. Spire.PDF offers flexible image compression options that allow you to reduce file size by compressing either all images or individual images in the document.

Example 1: Compress All Images with PdfCompressor

You can compress the images in a PDF document by creating a PdfCompressor object, enabling CompressImage and ResizeImages properties, and setting the ImageQuality to a predefined level such as Low, Medium, or High.

using Spire.Pdf.Conversion.Compression;

namespace CompressImages
{
    class Program
    {
        static void Main(string[] args)
        {
            // Create a PdfCompressor object and load the PDF file
            PdfCompressor compressor = new PdfCompressor("C:\\Users\\Administrator\\Documents\\Example.pdf");

            // Get the image compression options
            ImageCompressionOptions imageCompression = compressor.Options.ImageCompressionOptions;

            // Enable Image resizing
            imageCompression.ResizeImages = true;

            // Enable image compression
            imageCompression.CompressImage = true;

            // Set the image quality to Medium (available options: Low, Medium, High)
            imageCompression.ImageQuality = ImageQuality.Medium;


            // Compress the PDF file according to the compression options and save it to a new file
            compressor.CompressToFile("Compressed.pdf");
        }
    }
}

Compress images in PDF using C# with Spire.PDF

Example 2: Compress Images Individually Using TryCompressImage()

If you need more precise control over image compression, you can use the PdfImageHelper class to access the images on each page and compress them individually using the TryCompressImage() method.

using Spire.Pdf;
using Spire.Pdf.Utilities;

namespace CompressImagesIndividually
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();
            // Load the PDF file
            pdf.LoadFromFile("C:\\Users\\Administrator\\Documents\\Example.pdf");

            // Disable the incremental update
            pdf.FileInfo.IncrementalUpdate = false;

            // Create an instance of PdfImageHelper to work with images
            PdfImageHelper imageHelper = new PdfImageHelper();

            // Iterate through each page in the document
            foreach (PdfPageBase page in pdf.Pages)
            {
                // Retrieve information about the images on the page
                foreach (PdfImageInfo info in imageHelper.GetImagesInfo(page))
                {
                    // Attempt to compress the image
                    info.TryCompressImage();
                }
            }

            // Save the updated file
            pdf.SaveToFile("Compressed.pdf");
            pdf.Close();
        }
    }
}

Method 2. Optimize Fonts

Fonts embedded in a PDF file can contribute significantly to its size, especially when multiple fonts or large font sets are used. You can compress or unembed fonts that aren't essential for document rendering through the TextCompressionOptions property.

using Spire.Pdf.Conversion.Compression;

namespace OptimizeFonts
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a PdfCompressor object and load the PDF file
            PdfCompressor compressor = new PdfCompressor("C:\\Users\\Administrator\\Documents\\Example.pdf");

            // Get the text compression options
            TextCompressionOptions textCompression = compressor.Options.TextCompressionOptions;

            // Compress the fonts
            textCompression.CompressFonts = true;

            // Unembed the fonts
            // textCompression.UnembedFonts = true;

            // Compress the PDF file according to the compression options and save it to a new file
            compressor.CompressToFile("CompressFonts.pdf");
        }
    }
}

Method 3. Optimizing Document Content

Beyond images and fonts, overall document content can be optimized by setting the CompressionLevel property of the document to PdfCompressionLevel.Best.

using Spire.Pdf;
using Spire.Pdf.Conversion.Compression;

namespace OptimizeDocumentContent
{
    internal class Program
    {
        static void Main(string[] args)
        {
            // Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();
            // Load the PDF file
            pdf.LoadFromFile("C:\\Users\\Administrator\\Documents\\Example.pdf");

            // Disable the incremental update
            pdf.FileInfo.IncrementalUpdate = false;

            // Set the compression level to best
            pdf.CompressionLevel = PdfCompressionLevel.Best;

            // Save the updated file
            pdf.SaveToFile("OptimizeDocumentContent.pdf");
            pdf.Close();
        }
    }
}

Conclusion

Compressing PDF files in C# using Spire.PDF for .NET is straightforward, efficient, and highly customizable. Whether your goal is to reduce file size for web uploads, email attachments, or storage management, this library offers flexible solutions such as:

  • Compressing images
  • Optimizing fonts
  • Minimizing document content

By applying one or a combination of these techniques, you can significantly reduce PDF file sizes while preserving readability and document structure—making your files easier to share, store, and distribute.

FAQs

Q1: Is it possible to compress PDF files in bulk?

A1: Yes. You can loop through multiple PDF files in a directory and apply compression using the same logic programmatically.

Q2: Can I compress a PDF and then convert it to PDF/A or other formats?

A2: Absolutely. You can compress the PDF first, then convert it to PDF/A, ensuring long-term archival with optimized size.

Q3: Can I preserve hyperlinks, bookmarks, and metadata during compression?

A3: Yes. Compression will not remove document structure like links, bookmarks, or metadata. Spire.PDF preserves document integrity.

Q4: Does Spire.PDF support other PDF operations besides compression?

A4: Yes. Besides compression, Spire.PDF offers a wide range of PDF features, such as:

  • Merging/Splitting PDFs
  • Extracting text, images and tables
  • Adding watermarks
  • Digitally signing and encrypting PDFs

For detailed tutorials and sample projects, you can visit the Spire.PDF tutorial page and explore the GitHub demo repository to see practical code examples.

Get a Free License

To fully experience the capabilities of Spire.PDF for .NET without any evaluation limitations, you can request a free 30-day trial license.

A doughnut chart (also spelled donut) is a variant of the pie chart, with a blank center allowing for additional information about the data as a whole to be included. In this article, you will learn how to create a doughnut chart in PowerPoint using Spire.Presentation.

Step 1: Initialize an instance of Presentation class.

Presentation presentation = new Presentation();

Step 2: Insert a Doughnut chart in the first slide and set the chart title.

RectangleF rect = new RectangleF(40, 100, 550, 320);
IChart chart = presentation.Slides[0].Shapes.AppendChart(ChartType.Doughnut, rect, false);
chart.ChartTitle.TextProperties.Text = "Market share by country";
chart.ChartTitle.TextProperties.IsCentered = true;
chart.ChartTitle.Height = 30;

Step 3: Define the chart data.

string[] countries = new string[] { "Guba", "Mexico","France","German" };
int[] sales = new int[] { 1800, 3000, 5100, 6200 };
chart.ChartData[0, 0].Text = "Countries";
chart.ChartData[0, 1].Text = "Sales";
for (int i = 0; i < countries.Length; ++i)
{
    chart.ChartData[i + 1, 0].Value = countries[i];
    chart.ChartData[i + 1, 1].Value = sales[i];
}

Step 4: Set the data range of category labels, series label and series values.

chart.Series.SeriesLabel = chart.ChartData["B1", "B1"];
chart.Categories.CategoryLabels = chart.ChartData["A2", "A5"];
chart.Series[0].Values = chart.ChartData["B2", "B5"];

Step 5: Add data points to series and fill each data point with different color.

for (int i = 0; i < chart.Series[0].Values.Count; i++)
{
    ChartDataPoint cdp = new ChartDataPoint(chart.Series[0]);
    cdp.Index = i;
    chart.Series[0].DataPoints.Add(cdp);
}
chart.Series[0].DataPoints[0].Fill.FillType = FillFormatType.Solid;
chart.Series[0].DataPoints[0].Fill.SolidColor.Color = Color.LightBlue;
chart.Series[0].DataPoints[1].Fill.FillType = FillFormatType.Solid;
chart.Series[0].DataPoints[1].Fill.SolidColor.Color = Color.MediumPurple;
chart.Series[0].DataPoints[2].Fill.FillType = FillFormatType.Solid;
chart.Series[0].DataPoints[2].Fill.SolidColor.Color = Color.DarkGray;
chart.Series[0].DataPoints[3].Fill.FillType = FillFormatType.Solid;
chart.Series[0].DataPoints[3].Fill.SolidColor.Color = Color.DarkOrange;

Step 6: Display value and percentage in data labels.

chart.Series[0].DataLabels.LabelValueVisible = true;
chart.Series[0].DataLabels.PercentValueVisible = true;

Step 7: Adjust the hole size of doughnut chart.

chart.Series[0].DoughnutHoleSize = 60;

Step 8: Save the file.

presentation.SaveToFile("DoughnutChart.pptx", FileFormat.Pptx2013);

Output:

How to Create Doughnut Chart in PowerPoint in C#

Full Code:

using Spire.Presentation;
using Spire.Presentation.Charts;
using Spire.Presentation.Drawing;
using System.Drawing;

namespace SetFont
{
    class Program
    {
        static void Main(string[] args)
        {
            Presentation presentation = new Presentation();
            RectangleF rect = new RectangleF(40, 100, 550, 320);
            IChart chart = presentation.Slides[0].Shapes.AppendChart(ChartType.Doughnut, rect, false);
            chart.ChartTitle.TextProperties.Text = "Market share by country";
            chart.ChartTitle.TextProperties.IsCentered = true;
            chart.ChartTitle.Height = 30;

            string[] countries = new string[] { "Guba", "Mexico", "France", "German" };
            int[] sales = new int[] { 1800, 3000, 5100, 6200 };
            chart.ChartData[0, 0].Text = "Countries";
            chart.ChartData[0, 1].Text = "Sales";
            for (int i = 0; i < countries.Length; ++i)
            {
                chart.ChartData[i + 1, 0].Value = countries[i];
                chart.ChartData[i + 1, 1].Value = sales[i];
            }
            chart.Series.SeriesLabel = chart.ChartData["B1", "B1"];
            chart.Categories.CategoryLabels = chart.ChartData["A2", "A5"];
            chart.Series[0].Values = chart.ChartData["B2", "B5"];

            for (int i = 0; i < chart.Series[0].Values.Count; i++)
            {
                ChartDataPoint cdp = new ChartDataPoint(chart.Series[0]);
                cdp.Index = i;
                chart.Series[0].DataPoints.Add(cdp);
            }
            chart.Series[0].DataPoints[0].Fill.FillType = FillFormatType.Solid;
            chart.Series[0].DataPoints[0].Fill.SolidColor.Color = Color.LightBlue;
            chart.Series[0].DataPoints[1].Fill.FillType = FillFormatType.Solid;
            chart.Series[0].DataPoints[1].Fill.SolidColor.Color = Color.MediumPurple;
            chart.Series[0].DataPoints[2].Fill.FillType = FillFormatType.Solid;
            chart.Series[0].DataPoints[2].Fill.SolidColor.Color = Color.DarkGray;
            chart.Series[0].DataPoints[3].Fill.FillType = FillFormatType.Solid;
            chart.Series[0].DataPoints[3].Fill.SolidColor.Color = Color.DarkOrange;

            chart.Series[0].DataLabels.LabelValueVisible = true;
            chart.Series[0].DataLabels.PercentValueVisible = true;
            chart.Series[0].DoughnutHoleSize = 60;

            presentation.SaveToFile("DoughnutChart.pptx", FileFormat.Pptx2013);
        }
    }
}

How to remove page breaks in a worksheet

2017-02-23 07:25:37 Written by Koohji

We have already demonstrated how to add page breaks in Excel worksheet in C# with the help of Spire.XLS. Spire.XLS supports to remove all the horizontal and vertical page breaks and it also supports to remove the special page breaks. Here comes to the steps of how to remove the page breaks from an Excel worksheet.

Firstly, view the same Excel document with horizontal page breaks and vertical page breaks:

How to remove page breaks in a worksheet

Step 1: Initialize an instance of Workbook and load the document from file.

Workbook workbook = new Workbook();
workbook.LoadFromFile("Sample.xlsx");

Step 2: Get the first worksheet from the workbook.

Worksheet sheet = workbook.Worksheets[0];

Step 3: Clear all the vertical page breaks by call the VPageBreaks.Clear() method.

sheet.VPageBreaks.Clear();

Step 4: Remove the specified horizontal Page Break by call the HPageBreaks.RemoveAt() method.

sheet.HPageBreaks.RemoveAt(0);

Step 5: Set the ViewMode as Preview to see how the page breaks work.

sheet.ViewMode = ViewMode.Preview;

Step 6: Save the document to file.

workbook.SaveToFile("RemovePageBreak.xlsx", FileFormat.Version2010);

Effective screenshot of removing the page breaks in a worksheet:

How to remove page breaks in a worksheet

Full codes:

using Spire.Xls;
namespace RemovePageBreak
{
    class Program
    {

        static void Main(string[] args)
        {
            Workbook workbook = new Workbook();
            workbook.LoadFromFile("Sample.xlsx");

            Worksheet sheet = workbook.Worksheets[0];

            //sheet.HPageBreaks.Clear();
            sheet.VPageBreaks.Clear();

            sheet.HPageBreaks.RemoveAt(0);


            sheet.ViewMode = ViewMode.Preview;

            workbook.SaveToFile("RemovePageBreak.xlsx", FileFormat.Version2010);
        }
    }
}

Replace font(s) in PDF document

2017-02-22 09:12:35 Written by Koohji

Spire.PDF supports the functionality to replace font(s) used in PDF document. The following parts shows how we can use Spire.PDF to replace all the fonts used in an existing PDF document with another alternate font in C# and VB.NET.

Screenshot before replacing font:

How to replace font(s) in PDF document

Code snippets:

Step 1: Instantiate an object of PdfDocument class and load the PDF document.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile(@"E:\Program Files\input.pdf");

Step 2: Use the UsedFonts attribute of PdfDocument class to get all the fonts used in the document.

PdfUsedFont[] fonts = doc.UsedFonts;

Step 3: Create a new PDF font. Loop through the fonts and call PdfUsedFont.replace() method to replace them with the new font.

PdfFont newfont = new PdfFont(PdfFontFamily.TimesRoman, 11f, PdfFontStyle.Italic | PdfFontStyle.Bold);
foreach (PdfUsedFont font in fonts)
{
    font.Replace(newfont);
}

Step 4: Save the resultant document.

doc.SaveToFile("output.pdf");

Screenshot after replacing font:

How to replace font(s) in PDF document

Full code:

[C#]
using System.Drawing;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Graphics.Fonts;

namespace Replace_font_in_PDF
{
    class Program
    {
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile(@"E:\Program Files\input.pdf");
            PdfUsedFont[] fonts = doc.UsedFonts;
            PdfFont newfont = new PdfFont(PdfFontFamily.TimesRoman, 11f, PdfFontStyle.Italic | PdfFontStyle.Bold);
            foreach (PdfUsedFont font in fonts)
            {
                font.Replace(newfont);
            }

            doc.SaveToFile("output.pdf");
        }
    }
}
[VB.NET]
Imports System.Drawing
Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports Spire.Pdf.Graphics.Fonts

Namespace Replace_font_in_PDF
	Class Program
		Private Shared Sub Main(args As String())
			Dim doc As New PdfDocument()
			doc.LoadFromFile("E:\Program Files\input.pdf")
			Dim fonts As PdfUsedFont() = doc.UsedFonts
			Dim newfont As New PdfFont(PdfFontFamily.TimesRoman, 11F, PdfFontStyle.Italic Or PdfFontStyle.Bold)
			For Each font As PdfUsedFont In fonts
				font.Replace(newfont)
			Next

			doc.SaveToFile("output.pdf")
		End Sub
	End Class
End Namespace

C#/VB.NET: Flatten Form Fields in PDF

2022-08-15 09:07:00 Written by Koohji

Flattening form fields is an efficient way to prevent others from modifying or deleting the form field contents in PDF. After flattening, the editing or filling capability of the form fields will be removed and their contents will appear as regular text. In this article, you will learn how to flatten form fields in a PDF document in C# and VB.NET 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

Flatten a Specific Form Field in PDF in C# and VB.NET

The following are the steps to flatten a specific form field in a PDF document using Spire.PDF for .NET:

  • Initialize an instance of PdfDocument class.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Get the form widget collection from the document.
  • Get a specific form field from the widget collection by its name or index through PdfFormWidget.FieldsWidget["fieldName"] property or PdfFormWidget.FieldsWidget.List[fieldIndex] property.
  • Flatten the form field through PdfField.Flatten property.
  • Save the result document using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Fields;
using Spire.Pdf.Widget;

namespace FlattenSpecificFormField
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();
            //Load a PDF document
            pdf.LoadFromFile("Form.pdf");

            //Get the form widget collection
            PdfFormWidget formWidget = (PdfFormWidget)pdf.Form;
            //Get a specific form field by its name
            PdfField form = formWidget.FieldsWidget["Address"];
            //Get a specific form field by its index
            //PdfField form = formWidget.FieldsWidget.List[2] as PdfField;
            //Flatten the form
            form.Flatten = true;

            //Save the result document
            pdf.SaveToFile("FlattenSpecific.pdf");
        }
    }
}

C#/VB.NET:  Flatten Form Fields in PDF

Flatten All Form Fields in PDF in C# and VB.NET

The following are the steps to flatten all the form fields in a PDF document using Spire.PDF for .NET:

  • Initialize an instance of PdfDocument class.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Flatten all the form fields in the document through PdfDocument.Form.IsFlatten property.
  • Save the result document using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;

namespace FlattenAllFormFields
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();
            //Load a PDF document
            pdf.LoadFromFile("Form.pdf");

            //Flatten all the forms in the document
            pdf.Form.IsFlatten = true;

            //Save the result document
            pdf.SaveToFile("FlattenAll.pdf");
        }
    }
}

C#/VB.NET:  Flatten Form Fields in 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.

Fill XFA Form Fields in C#/VB.NET

2017-02-14 07:54:06 Written by Administrator

XFA forms are XML-based forms created by Adobe's LiveCycle Designer tool, which offer enhanced features over the old AcroForms, like changeable text fields and support for running JavaScript. Spire.PDF supports to access the XFA forms in an existing PDF file and fill the fields with data.

Step 1: Initialize an instance of PdfDocument class and load a sample PDF file containing dynamic XFA forms.

PdfDocument doc = new PdfDocument();
doc.LoadFromFile("DynamicXFA.pdf");

Step 2: Get all form widgets from the document.

PdfFormWidget formWidget = doc.Form as PdfFormWidget;

Step 3: Get a list of XFA Fields.

List<XfaField> xfafields = formWidget.XFAForm.XfaFields;

Step 4: Traverse each XfaField in the list and judge if it is an XfaTextField, if yes, convert the type of XfaField as an XfaTextField and then assign value to the field based on the field name.

foreach (XfaField xfaField in xfaFields)
{
    if (xfaField is XfaTextField)
    {
        XfaTextField xf = xfaField as XfaTextField;
        switch (xfaField.Name)
        {
            case "EmployeeName":
                xf.Value = "Gary";
                break;
            case "Address":
                xf.Value = "Chengdu, China";
                break;
            case "StateProv":
                xf.Value = "Sichuan Province";
                break;
            case "ZipCode":
                xf.Value = "610093";
                break;
            case "SSNumber":
                xf.Value = "000-00-0000";
                break;
            case "HomePhone":
                xf.Value = "86-028-81705109";
                break;
            case "CellPhone":
                xf.Value = "123456789";
                break;
            case "Comments":
                xf.Value = "This demo shows how to fill XFA forms using Spire.PDF";
                break;
            default:
                break;
        }
    }
}

Step 5: Save the file.

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

Output:

How to Fill XFA Form Fields in C#, VB.NET

Full Code:

[C#]
using Spire.Pdf;
using Spire.Pdf.Widget;
using System.Collections;
using System.Collections.Generic;

namespace FillXFAFormFields
{
    class Program
    {
        private static IEnumerable xfaFields;
        static void Main(string[] args)
        {
            PdfDocument doc = new PdfDocument();
            doc.LoadFromFile("DynamicXFA.pdf");

            PdfFormWidget formWidget = doc.Form as PdfFormWidget;
            List <xfafields> = formWidget.XFAForm.XfaFields;
            foreach (XfaField xfaField in xfafields)
            {
                if (xfaField is XfaTextField)
                {
                    XfaTextField xf = xfaField as XfaTextField;
                    switch (xfaField.Name)
                    {
                        case "EmployeeName":
                            xf.Value = "Gary";
                            break;
                        case "Address":
                            xf.Value = "Chengdu, China";
                            break;
                        case "StateProv":
                            xf.Value = "Sichuan Province";
                            break;
                        case "ZipCode":
                            xf.Value = "610093";
                            break;
                        case "SSNumber":
                            xf.Value = "000-00-0000";
                            break;
                        case "HomePhone":
                            xf.Value = "86-028-81705109";
                            break;
                        case "CellPhone":
                            xf.Value = "123456789";
                            break;
                        case "Comments":
                            xf.Value = "This demo shows how to fill XFA forms using Spire.PDF";
                            break;
                        default:
                            break;
                    }
                }
            }
            doc.SaveToFile("FillXfaField.pdf", FileFormat.PDF);
        }
    }
}
[VB.NET]
Imports Spire.Pdf
Imports Spire.Pdf.Widget
Imports System.Collections.Generic


Namespace FillXFAFormFields
	Class Program
		Private Shared xfaFields As IEnumerable(Of XfaField)
		Private Shared Sub Main(args As String())
			Dim doc As New PdfDocument()
			doc.LoadFromFile("DynamicXFA.pdf")

			Dim formWidget As PdfFormWidget = TryCast(doc.Form, PdfFormWidget)
			Dim xfafields__1 As List(Of XfaField) = formWidget.XFAForm.XfaFields
			For Each xfaField As XfaField In xfaFields
				If TypeOf xfaField Is XfaTextField Then
					Dim xf As XfaTextField = TryCast(xfaField, XfaTextField)
					Select Case xfaField.Name
						Case "EmployeeName"
							xf.Value = "Gary"
							Exit Select
						Case "Address"
							xf.Value = "Chengdu, China"
							Exit Select
						Case "StateProv"
							xf.Value = "Sichuan Province"
							Exit Select
						Case "ZipCode"
							xf.Value = "610093"
							Exit Select
						Case "SSNumber"
							xf.Value = "000-00-0000"
							Exit Select
						Case "HomePhone"
							xf.Value = "86-028-81705109"
							Exit Select
						Case "CellPhone"
							xf.Value = "123456789"
							Exit Select
						Case "Comments"
							xf.Value = "This demo shows how to fill XFA forms using Spire.PDF"
							Exit Select
						Case Else
							Exit Select
					End Select
				End If
			Next
			doc.SaveToFile("FillXfaField.pdf", FileFormat.PDF)
		End Sub
	End Class
End Namespace
page 31