As a standalone component, compatible with all .NET developing platforms, Spire.PDF for .NET enables developers to create, read, write, edit and handle PDF files without any external PDF reader or software its alike. In this section, I’ll introduce you how to create a PDF file and save it to stream, and how to load PDF file from stream on the contrary.

Part I. Create PDF file and save it to stream

Step 1: New a PDF instance.

PdfDocument doc = new PdfDocument();

Step 2: Create one page.

PdfPageBase page = doc.Pages.Add();

Step 3: Add text to that page.

page.Canvas.DrawString("Hello, World!",
                        new PdfFont(PdfFontFamily.Helvetica, 30f),
                        new PdfSolidBrush(Color.Black),
                        10, 10);

Step 4: Save PDF file to Stream.

FileStream to_strem = new FileStream("To_stream.pdf", FileMode.Open);
doc.SaveToStream(to_stream);
to_stream.Close();
doc.Close();

Part II. Load PDF file from stream

Step 1: New a PDF instance.

PdfDocument doc = new PdfDocument();

Step 2: Load PDF file from stream.

FileStream from_stream = File.OpenRead("sample.pdf");
doc.LoadFromStream(from_stream);

Step 3: Save the PDF document.

doc.SaveToFile("From_stream.pdf",FileFormat.PDF);
System.Diagnostics.Process.Start("From_stream.pdf");

Full Code:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Spire.Pdf;
using System.IO;
using Spire.Pdf.Graphics;
using System.Drawing;

namespace PdfAndStream
{
    class Program
    {
        static void Main(string[] args)
        {
            //A: create PDF file and save it to stream

            //create a pdf document.
            PdfDocument doc = new PdfDocument();

            // create one page
            PdfPageBase page = doc.Pages.Add();

            //draw the text
            page.Canvas.DrawString("Hello, World!",
                                   new PdfFont(PdfFontFamily.Helvetica, 30f),
                                   new PdfSolidBrush(Color.Black),
                                   10, 10);   
    
            //save pdf file to Stream
            FileStream to_stream = new FileStream("To_stream.pdf", FileMode.Open);
            doc.SaveToStream(to_stream);
            to_stream.Close();
            doc.Close();

            System.Diagnostics.Process.Start("To_stream.pdf");

            
            //B: Load PDF file from Stream

            //create a pdf document.
            PdfDocument docFrom = new PdfDocument();

            //load PDF file from stream
            FileStream from_stream = File.OpenRead("sample.pdf");
            docFrom.LoadFromStream(from_stream);
            
            //save the pdf document
            docFrom.SaveToFile("From_stream.pdf",FileFormat.PDF);

            System.Diagnostics.Process.Start("From_stream.pdf");


        }
    }
}

Besides loading PDF document from stream, Spire.PDF also provide easy access to load PDF document from file and byte array. See Spire.PDF Program Guide, to get more info regarding processing PDF in C#, VB.NET.

Published in Document Operation

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.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.

Published in Document Operation

PDF/A is widely used for long term archiving for PDF format. By using Spire.PDF, you can create PDF/A file directly. This article mainly shows how to set up PDF/A file; it will also demonstrate how to add image and insert hyperlink to image in C#.

Make sure Spire.PDF for .NET (version 2.9.43 or above) has been installed correctly and then add Spire.Pdf.dll as reference in the downloaded Bin folder though the below path: "..\Spire.Pdf\Bin\NET4.0\ Spire.Pdf.dll".

Here comes to the steps:

Step 1: Create a PDF/A document.

// create a PDF/A document and add contents to it
PdfDocument document = new PdfDocument(PdfConformanceLevel.Pdf_A1B);
PdfPageBase page = document.Pages.Add();
page.Canvas.DrawString("Hello World", new PdfFont(PdfFontFamily.Helvetica, 30f), new PdfSolidBrush(Color.Black), 10, 10);

Step 2: Load an image from file and insert to the PDF.

//insert an image
PdfImage image = PdfImage.FromFile(@"D:\PDF.png");

Step 3: Add a hyper link to the image.

//Add a link to image
PointF location = new PointF(100, 100);
RectangleF linkBounds = new RectangleF(location, new SizeF(image.Width, image.Height));
Spire.Pdf.Annotations.PdfUriAnnotation link = new Spire.Pdf.Annotations.PdfUriAnnotation(linkBounds, "http://www.e-iceblue.com/Introduce/pdf-for-net-introduce.html");
link.Border = new PdfAnnotationBorder(0);
page.Canvas.DrawImage(image, linkBounds);
page.AnnotationsWidget.Add(link);

Step 4: Save the PDF document.

//Save the document to file in PDF format
document.SaveToFile("PDFA.pdf");

Effective screenshot:

Create PDF/A and insert hyperlink to image

Published in Document Operation
Monday, 28 August 2023 07:05

C#/VB.NET: Change PDF Version

When uploading or submitting PDF files on certain platforms, you are sometimes faced with the dilemma that the platforms require a specific version of PDF file. If your PDF files fail to meet the requirements, it is necessary to convert them to a different version for compatibility purposes. This article will demonstrate how to programmatically convert PDF between different versions 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 DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Change PDF Version in C# and VB.NET

Spire.PDF for .NET supports PDF versions from 1.0 to 1.7. To convert a PDF file to a newer or older version, you can use the PdfDocument.FileInfo.Version property. The following are the detailed steps.

  • Create a PdfDocument object.
  • Load a sample PDF file using PdfDocument.LoadFromFile() method.
  • Change the PDF version to a newer or older version using PdfDocument.FileInfo.Version property.
  • Save the result document using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;

namespace ConvertPDFVersion
{
    class Program
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument object
            PdfDocument pdf = new PdfDocument();

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

            //Change the PDF to version 1.7
            pdf.FileInfo.Version = PdfVersion.Version1_7;

            //Save the result file
            pdf.SaveToFile("PDFVersion.pdf");
        }
    }
}

C#/VB.NET: Change PDF Version

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.

Published in Document Operation
Thursday, 02 June 2022 08:01

C#/VB.NET: Merge PDF Documents

There are many reasons merging PDFs may be necessary. For example, merging PDF files allows you to print a single file rather than queueing several documents for the printer, combining related files simplifies the process of managing and storing many documents by reducing the number of files to search through and organize. In this article, you will learn how to merge multiple PDF documents into one PDF document and how to combine the selected pages from different PDF documents into one PDF in C# and VB.NET by 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

Merge Multiple PDFs into a Single PDF

Spire.PDF for .NET offers the PdfDocument.MergeFiles() method to merge multiple PDF documents into a single document. The detailed steps are as follows.

  • Get the paths of the documents to be merged and store them in a string array.
  • Call PdfDocument.MergeFiles() method to merge these files.
  • Save the result to a PDF document using PdfDocumentBase.Save() method.
  • C#
  • VB.NET
using System;
using Spire.Pdf;

namespace MergePDFs
{
    class Program
    {
        static void Main(string[] args)
        {
            //Get the paths of the documents to be merged
            String[] files = new String[] {
                "C:\\Users\\Administrator\\Desktop\\PDFs\\sample-1.pdf",
                "C:\\Users\\Administrator\\Desktop\\PDFs\\sample-2.pdf",
                "C:\\Users\\Administrator\\Desktop\\PDFs\\sample-3.pdf"};

            //Merge these documents and return an object of PdfDocumentBase
            PdfDocumentBase doc = PdfDocument.MergeFiles(files);

            //Save the result to a PDF file
            doc.Save("output.pdf", FileFormat.PDF);
        }
    }
}

C#/VB.NET: Merge PDF Documents

Merge the Selected Pages of Different PDFs into One PDF

Spire.PDF for .NET offers the PdfDocument.InsertPage() method and the PdfDocument.InsertPageRange() method to import a page or a page range from one PDF document to another. The following are the steps to combine the selected pages from different PDF documents into a new PDF document.

  • Get the paths of the source documents and store them in a string array.
  • Create an array of PdfDocument, and load each source document to a separate PdfDocument object.
  • Create another PdfDocument object for generating a new document.
  • Insert the selected page or page range of the source documents to the new document using PdfDocument.InsertPage() method and PdfDocument.InsertPageRange() method.
  • Save the new document to a PDF file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using System;
using Spire.Pdf;

namespace MergeSelectedPages
{
    class Program
    {
        static void Main(string[] args)
        {
            //Get the paths of the documents to be merged
            String[] files = new String[] {
                "C:\\Users\\Administrator\\Desktop\\PDFs\\sample-1.pdf",
                "C:\\Users\\Administrator\\Desktop\\PDFs\\sample-2.pdf",
                "C:\\Users\\Administrator\\Desktop\\PDFs\\sample-3.pdf"};

            //Create an array of PdfDocument
            PdfDocument[] docs = new PdfDocument[files.Length];

            //Loop through the documents
            for (int i = 0; i < files.Length; i++)
            {
                //Load a specific document
                docs[i] = new PdfDocument(files[i]);
            }

            //Create a PdfDocument object for generating a new PDF document
            PdfDocument doc = new PdfDocument();

            //Insert the selected pages from different documents to the new document
            doc.InsertPage(docs[0], 0);
            doc.InsertPageRange(docs[1], 1,3);
            doc.InsertPage(docs[2], 0);

            //Save the document to a PDF file
            doc.SaveToFile("output.pdf");
        }
    }
}

C#/VB.NET: Merge PDF Documents

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.

Published in Document Operation

About PDF

Portable Document Format (PDF)is a fixed-layout document as an independent specification by Adobe. It encapsulates a complete description including the text fonts, graphics, and other information needed to display it.

Create PDF dynamically and send it to client browser

To generate a PDF file dynamically and then send it to client browser, you can use Spire.PDF for .NET to finish this task. In addition, Spire.PDF supports loading an existing PDF file and send it to client browser as well. In this technical article, we will combine both two functions to made a fully description about how Spire.PDF make it work. Below are the two tasks:

  • Task1 Create PDF dynamically and send it to client browser.
  • Task2 Load an Existing PDF file and send it to client browser(This is an additional function of Spire.PDF for .NET)

Firstly create an Asp.net application and add Spire.PDF.dll assembly. You can add two buttons on an Aspx page in VS. Appoint one of them for Task 1, and the other for Task 2.

In terms of Task 1, firstly you need initiate an object of Spire.PdfDocument

[C#]
PdfDocument doc = new PdfDocument();

And add a new page in this new PDF document

[C#]
PdfPageBase page = newDoc.Pages.Add();

Pay attention that related auxiliary object are need while drawing string on this pdf page.

[C#]
string message = "Hello world!";
PdfFont font = new PdfFont(PdfFontFamily.Helvetica, 13f);
PdfBrush brush = PdfBrushes.Red;
PointF location = new PointF(20, 20);

Then you can draw a string in pdf page, something like this:

[C#]
page.Canvas.DrawString(message, font, brush, location);

Finally you can open this newly generated PDF document in Client browser:

[C#]
newDoc.SaveToHttpResponse("sample.pdf",HttpContext.Current.Response, HttpReadType.Open);

When it comes to Task 2, 3 lines of code can work it out directly.

Initiated an object of Spire.PdfDocument

[C#]
pdfDocument doc = new PdfDocument();

Load a pdf file

[C#]
doc.LoadFromFile(this.Server.MapPath("/sample.pdf"));

Load a pdf document ,after that ,send it to client browser as an attachment.

[C#]
doc.SaveToHttpResponse("sample.pdf", this.Response, HttpReadType.Save);

To summarize above, the following is the complete code snippet needed in this two tasks:

[C#]
C#
using System;
using System.Collections.Generic;
using System.Drawing;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Spire.Pdf;
using Spire.Pdf.Graphics;

namespace SendPdfToWebBrowser
{
    public partial class WebForm_SendPdf : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {         
            
        }
        // load a pdf document ,after that ,send it to client browser as an attachment
        protected void btnClientSavePdf_Click(object sender,EventArgs e)
        {

           // initiated an object of Spire.PdfDocument
            PdfDocument doc = new PdfDocument();
            // Load a pdf file 

            doc.LoadFromFile(this.Server.MapPath("/sample.pdf"));
            // send the pdf document to client browser as an attachment
            doc.SaveToHttpResponse("sample.pdf",this.Response, HttpReadType.Save);
        }

        // Create an pdf document ,then open it in the client browser
        protected void btnClientOpenPdf_Click(object sender, EventArgs e)
        {
            // Initiate an object of Spire.PdfDocument
            PdfDocument newDoc = new PdfDocument();
            // Add a new page in this newly created pdf file
            PdfPageBase page = newDoc.Pages.Add();
            string message = "Hello world!” ;
 
            PdfFont font = new PdfFont(PdfFontFamily.Helvetica,13f);
            PdfBrush brush = PdfBrushes.Red;
            PointF location = new PointF(20, 20);
            // Draw a string with designated brush, a font, position in pdf page
            page.Canvas.DrawString(message, font, brush, location);
            //To open this pdf document in client browser.
            newDoc.SaveToHttpResponse("sample.pdf",HttpContext.Current.Response, HttpReadType.Open);
        }
    }
}

In the end, you can run it, and get things like this:

Screenshot of creating PDF dynamically and sending it to client browser

Screenshot of Loading an Existing PDF file and sending it to client browser

Published in Document Operation
Thursday, 11 August 2022 07:25

C#/VB.NET: Create Lists in PDF Documents

A list is a collection of related values written one after another. Lists are the best tool to make important information stand out on the page, show the steps in a process, or present an overview to the readers. In this article, you will learn how to create ordered or unordered lists in a PDF document in C# and VB.NET using Spire.PDF for .NET.

Spire.PDF provides the PdfSortedList class and the PdfList class to represent the ordered lists and unordered lists, respectively. To set the list's content, indent, font, marker style and other attributes, use the methods, properties, or events under these two classes. The following table lists some of the core items involved in this tutorial.

Member Description
PdfSortedList class Represents an ordered list in a PDF document.
PdfList class Represents an unordered list in a PDF document.
Brush property Gets or sets a list's brush.
Font property Gets or sets a list's font.
Indent property Gets or sets a list's indent.
TextIndent property Gets or sets the indent from the marker to the list item text.
Items property Gets items of a list.
Marker property Gets or sets the marker of a list.
Draw() method Draw list on the canvas of a page at the specified location.
PdfOrderedMarker class Represents the marker style of an ordered list, such as numbers, letters, and roman numerals.
PdfMarker class Represents bullet style for an unordered list.

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 DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Create an Ordered List in PDF

An ordered list is a container which holds a sequence of objects. Each item in the list is marked with a number, a letter, or a roman numeral. The following are the step to create an ordered list in PDF using Spire.PDF for .NET.

  • Create a PdfDocument object.
  • Add a page to it using PdfDocument.Pages.Add() method.
  • Create PdfBrush and PdfFont objects for the list.
  • Create a PdfOrderedMarker object, specifying the marker style.
  • Specify the list content with a string, and create an object of PdfSortedList class based on the string.
  • Set the font, indent, brush and marker of the list though the properties under the PdfSortedList object.
  • Draw the list on the page at the specified location using PdfSortedList.Draw() method.
  • Save the document to another file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using System;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Lists;

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

            //Set the margins
            PdfMargins margins = new PdfMargins(30);

            //Add a page
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margins);

            //Create a brush
            PdfBrush brush = PdfBrushes.Black;

            //Create fonts
            PdfFont titleFont = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Bold);
            PdfFont listFont = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Regular);

            //Create a maker for ordered list
            PdfOrderedMarker marker = new PdfOrderedMarker(PdfNumberStyle.LowerLatin, listFont);

            //Specify the initial coordinate
            float x = 10;
            float y = 20;

            //Draw title
            String title = "Required Web Development Skills:";
            page.Canvas.DrawString(title, titleFont, brush, x, y);
            y = y + (float)titleFont.MeasureString(title).Height;
            y = y + 5;


            //Create a numbered list
            String listContent = "Command-line Unix\n"
                + "Vim\n"
                + "HTML\n"
                + "CSS\n"
                + "Python\n"
                + "JavaScript\n"
                + "SQL";
            PdfSortedList list = new PdfSortedList(listContent);

            //Set the font, indent, text indent, brush of the list
            list.Font = listFont;
            list.Indent = 2;
            list.TextIndent = 4;
            list.Brush = brush;
            list.Marker = marker;

            //Draw list on the page at the specified location
            list.Draw(page, x, y);

            //Save to file
            doc.SaveToFile("OrderedList.pdf");
        }
    }
}

C#/VB.NET: Create Lists in PDF Documents

Create an Unordered List with Symbol Bullets in PDF

An unordered list, also named bulleted list, is a collection of related items that have no special order or sequence. Each item in the list is marked with a bullet. The following are the step to create an unordered list in PDF using Spire.PDF for .NET.

  • Create a PdfDocument object.
  • Add a page to it using PdfDocument.Pages.Add() method.
  • Create PdfBrush and PdfFont objects for the list.
  • Create a PdfMarker object, specifying the marker style.
  • Specify the list content with a string, and create an object of PdfList class based on the string.
  • Set the font, indent, brush and marker of the list though the properties under the PdfList object.
  • Draw the list on the page at the specified location using PdfList.Draw() method.
  • Save the document to another file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Lists;
using System;

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

            //Set the margin
            PdfMargins margin = new PdfMargins(30);

            //Add a page
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);

            //Create fonts
            PdfFont titleFont = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Bold);
            PdfFont listFont = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Regular);
            PdfFont markerFont = new PdfFont(PdfFontFamily.TimesRoman, 6f, PdfFontStyle.Regular);

            //Create a brush
            PdfBrush brush = PdfBrushes.Black;

            //Specify the initial coordinate
            float x = 10;
            float y = 20;

            //Draw title
            String title = "Computer Science Subjects:";
            page.Canvas.DrawString(title, titleFont, brush, x, y);
            y = y + (float)titleFont.MeasureString(title).Height;
            y = y + 5;

            //Specify the marker style
            PdfMarker marker = new PdfMarker(PdfUnorderedMarkerStyle.Asterisk);
            marker.Font = markerFont;

            //Create an unordered list
            String listContent = "Data Structure\n"
                    + "Algorithm\n"
                    + "Computer Networks\n"
                    + "Operating System\n"
                    + "Theory of Computations\n"
                    + "C Programming\n"
                    +"Computer Organization and Architecture"; 

            PdfList list = new PdfList(listContent);

            //Set the font, indent, text indent, brush, maker of the list
            list.Font = listFont;
            list.Indent = 2;
            list.TextIndent = 4;
            list.Brush = brush;
            list.Marker = marker;

            //Draw list on a page at the specified location
            list.Draw(page, x, y);

            //Save to file
            doc.SaveToFile("UnorderedList.pdf");
        }
    }
}

C#/VB.NET: Create Lists in PDF Documents

Create an Unordered List with Image Bullets in PDF

In addition to symbols, the bullet points of an unordered list can be also a picture. The steps to create an unordered list with images bullets are as follows.

  • Create a PdfDocument object.
  • Add a page to it using PdfDocument.Pages.Add() method.
  • Create PdfBrush and PdfFont objects for the list.
  • Create a PdfMarker object, setting the marker style as CustomImage.
  • Set an image as the mark through PdfMarker.Image property.
  • Specify the list content with a string, and create an object of PdfList class based on the string.
  • Set the font, indent, brush and marker of the list though the properties under the PdfList object.
  • Draw the list on the page at the specified location using PdfList.Draw() method.
  • Save the document to another file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using System;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Lists;

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

            //Set the margin
            PdfMargins margin = new PdfMargins(30);

            //Add a page
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);

            //Create fonts
            PdfFont titleFont = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Bold);
            PdfFont listFont = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Regular);

            //Create a brush
            PdfBrush brush = PdfBrushes.Black;

            //Specify the initial coordinate
            float x = 10;
            float y = 20;

            //Draw title
            String title = "Project Task To-Do List:";
            page.Canvas.DrawString(title, titleFont, brush, x, y);
            y = y + (float)titleFont.MeasureString(title).Height;
            y = y + 5;

            //Specify the marker style to image
            PdfMarker marker = new PdfMarker(PdfUnorderedMarkerStyle.CustomImage);

            //Set the image for the marker
            marker.Image = PdfImage.FromFile(@"C:\Users\Administrator\Desktop\checkmark.jpg");

            //Create an unordered list
            String listContent = "Define projects and tasks you're working on\n"
                    + "Assign people to tasks\n"
                    + "Define the priority levels of your tasks\n"
                    + "Keep track of the progress status of your tasks\n"
                    + "Mark tasks as done when completed";
            PdfList list = new PdfList(listContent);

            //Set the font, indent, text indent, brush, maker of the list
            list.Font = listFont;
            list.Indent = 2;
            list.TextIndent = 4;
            list.Brush = brush;
            list.Marker = marker;

            //Draw list on a page at the specified location
            list.Draw(page, x, y);

            //Save to file
            doc.SaveToFile("ImageBullets.pdf");
        }
    }
}

C#/VB.NET: Create Lists in PDF Documents

Create a Nested Numbered List in PDF

A nested list is a list that contains at least one sub list. Nested lists are used to present data in hierarchical structures. The following are the steps to create a nested numbered list in PDF using Spire.PDF for .NET.

  • Create a PdfDocument object.
  • Add a page to it using PdfDocument.Pages.Add() method.
  • Create a PdfOrderedMarker object, specifying the marker style as Numeric.
  • Specify the list content with a string, and create a parent list based on the string. And then set the font, indent, brush and marker of the list though the properties under the PdfSortedList object.
  • Repeat the above step to create sub lists and sub-sub lists.
  • Get the specific item of the parent list through PdfSortedList.Items[] property, and add a list to it as its sub list through PdfListItem.Sublist property.
  • Draw the list on the page at the specified location using PdfSortedList.Draw() method.
  • Save the document to another file using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using System;
using Spire.Pdf;
using Spire.Pdf.Graphics;
using Spire.Pdf.Lists;

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

            //Set the margin
            PdfMargins margin = new PdfMargins(30);

            //Add a page
            PdfPageBase page = doc.Pages.Add(PdfPageSize.A4, margin);

            //Specify the initial coordinate
            float x = 10;
            float y = 20;

            //Create two brushes
            PdfBrush blackBrush = PdfBrushes.Black;
            PdfBrush purpleBrush = PdfBrushes.Purple;

            //Create two fonts
            PdfFont titleFont = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Bold);
            PdfFont listFont = new PdfFont(PdfFontFamily.TimesRoman, 12f, PdfFontStyle.Regular);

            //Create a maker for ordered list
            PdfOrderedMarker marker = new PdfOrderedMarker(PdfNumberStyle.Numeric, listFont);

            //Draw title
            String title = "Below is a Nested Numbered List:";
            page.Canvas.DrawString(title, titleFont, blackBrush, x, y);
            y = y + (float)titleFont.MeasureString(title).Height;
            y = y + 5;

            //Create a parent list
            String parentListContent = "Parent Item 1\n"
                    + "Parent Item 2";
            PdfSortedList parentList = new PdfSortedList(parentListContent);
            parentList.Font = listFont;
            parentList.Indent = 2;
            parentList.Brush = purpleBrush;
            parentList.Marker = marker;

            //Create a sub list - "subList_1"
            String subListContent_1 = "Sub Item 1\n"
                    + "Sub Item 2\n"
                    + "Sub Item 3\n"
                    + "Sub Item 4";
            PdfSortedList subList_1 = new PdfSortedList(subListContent_1);
            subList_1.Indent = 12;
            subList_1.Font = listFont;
            subList_1.Brush = blackBrush;
            subList_1.Marker = marker;
            subList_1.MarkerHierarchy = true;

            //Create another sub list -"subList_2"
            String subListContent_2 = "Sub Item 1\n"
                    + "Sub Item 2\n"
                    + "Sub Item 3";
            PdfSortedList subList_2 = new PdfSortedList(subListContent_2);
            subList_2.Indent = 12;
            subList_2.Font = listFont;
            subList_2.Brush = blackBrush;
            subList_2.Marker = marker;
            subList_2.MarkerHierarchy = true;

            //Create a sub-sub list - "subList_1"
            String subSubListContent_1 = "Sub Sub Item 1\n"
                    + "Sub Sub Item 2";
            PdfSortedList subSubList = new PdfSortedList(subSubListContent_1);
            subSubList.Indent = 20;
            subSubList.Font = listFont;
            subSubList.Brush = blackBrush;
            subSubList.Marker = marker;
            subSubList.MarkerHierarchy = true;

            //Set subList_1 as sub list of the first item of parent list
            PdfListItem item_1 = parentList.Items[0];
            item_1.SubList = subList_1;

            //Set subList_2 as sub list of the second item of parent list
            PdfListItem item_2 = parentList.Items[1];
            item_2.SubList = subList_2;

            //Set subSubList as sub list of the first item of subList_1
            PdfListItem item_1_1 = subList_1.Items[0];
            item_1_1.SubList = subSubList;

            //Draw parent list
            parentList.Draw(page, x, y);

            //Save to file
            doc.SaveToFile("MultiLevelList.pdf");
        }
    }
}

C#/VB.NET: Create Lists in PDF Documents

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.

Published in List
Friday, 30 June 2023 06:13

C#/VB.NET: Set or Get PDF Properties

PDF properties are metadata that provide additional information about a PDF file. Typically, these properties include, but are not limited to, the title of the document, the author, keywords, subject and the application that created the document. When there are a large number of PDF files, adding properties is essential as it can make the files easily retrievable. In this article, you will learn how to programmatically set or get PDF properties 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 DLL files can be either downloaded from this link or installed via NuGet.

PM> Install-Package Spire.PDF

Set the Properties of a PDF File in C# and VB.NET

Basic PDF document properties such as title, author, subject and keywords make it easier for users to search or retrieve specific documents later on. The following are the detailed steps on how to set these properties using Spire.PDF for .NET.

  • Create a PdfDocument instance.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Get PDF properties using PdfDocument.DocumentInformation property, and then set values for specific document properties such as title, subject and author through Title, Subject and Author properties of PdfDocumentInformation class.
  • Save the result PDF file using PdfDocument.SaveToFile () method.
  • C#
  • VB.NET
using Spire.Pdf;

namespace PDFProperties
{
    class Properties
    {
        static void Main(string[] args)
        {
            //Create a PdfDocument instance
            PdfDocument pdf = new PdfDocument();

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

            //Set the title
            pdf.DocumentInformation.Title = "PDF (Portable Document Format)";

            //Set the author
            pdf.DocumentInformation.Author = "E-iceblue";

            //Set the subject
            pdf.DocumentInformation.Subject = "Set PDF Properties";

            //Set the keywords
            pdf.DocumentInformation.Keywords = "NET PDF, Properties, Document";

            //Set the producer name
            pdf.DocumentInformation.Producer = "Spire.PDF";

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

C#/VB.NET: Set or Get PDF Properties

Get the Properties of a PDF File in C# and VB.NET

To get specific PDF properties, you can use the corresponding properties under the PdfDocumentInformation class. The following are the detailed steps.

  • Create a PdfDocument instance.
  • Load a PDF file using PdfDocument.LoadFromFile() method.
  • Create a StringBuilder instance.
  • Get PDF properties using PdfDocument.DocumentInformation property, and then get specific document properties such as title, author, keyword using properties under PdfDocumentInformation class.
  • Append the extracted properties to the StringBuilder instance using StringBuilder.Append() method.
  • Write the StringBuilder to a TXT file using File.WriteAllText() method.
  • C#
  • VB.NET
using Spire.Pdf;
using System.IO;
using System.Text;

namespace GetPdfProperties

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

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

            //Create a StringBuilder instance
            StringBuilder content = new StringBuilder();

            //Get the PDF document properties and append them in the StringBuilder
            content.Append("Title: " + pdf.DocumentInformation.Title + "\r\n");
            content.Append("Author: " + pdf.DocumentInformation.Author + "\r\n");
            content.Append("Subject: " + pdf.DocumentInformation.Subject + "\r\n");
            content.Append("Keywords: " + pdf.DocumentInformation.Keywords + "\r\n");
            content.Append("PDF Producer: " + pdf.DocumentInformation.Producer + "\r\n");

            //Write the StringBuilder to a TXT file
            File.WriteAllText("GetPDFProperties.txt", content.ToString());
        }
    }
} 

C#/VB.NET: Set or Get PDF Properties

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.

Published in Document Operation

After searching so much information about PDF merge, it is easy to find that whether you merge PDF files online or use C#/VB.NET to realize this task, you never escape worrying some important points such as the safety of your PDF file, so much time it costs or whether the merged file supports to print page number and so on. However, as long as you come here, these troubles will not appear. This section will specifically introduce you a secure solution to merge PDF files into one with C#, VB.NET via a .NET PDF component Spire.PDF for .NET.

Spire.PDF for .NET, built from scratch in C#, enables programmers and developers to create, read, write and manipulate PDF documents in .NET applications without using Adobe Acrobat or any external libraries. Using Spire.PDF for .NET, you not only can quickly merge PDF files but also enables you to print PDF page with page number. Now please preview the effective screenshot below:

Merge PDF Documents

Before following below procedure, please download Spire.PDF for .NET and install it on system.

Step1: You can use the String array to save the names of the three PDF files which will be merged into one PDF and demonstrate Spire.Pdf.PdfDocument array. Then, load three PDF files and select the first PdfDocument for the purpose of merging the second and third PDF file to it. In order to import all pages from the second PDF file to the first PDF file, you need to call the method public void AppendPage(PdfDocument doc). Also by calling another method public PdfPageBase InsertPage(PdfDocument doc, int pageIndex),every page of the third PDF file can be imported to the first PDF file.

[C#]
private void button1_Click(object sender, EventArgs e)
        {
            //pdf document list
            String[] files = new String[]
            {
                @"..\PDFmerge0.pdf",
                @"..\ PDFmerge1.pdf",
                @"..\ PDFmerge2.pdf"
            };
            //open pdf documents            
            PdfDocument[] docs = new PdfDocument[files.Length];
            for (int i = 0; i < files.Length; i++)
            {
                docs[i] = new PdfDocument(files[i]);
            }
            //append document
            docs[0].AppendPage(docs[1]);

            //import PDF pages
            for (int i = 0; i < docs[2].Pages.Count; i = i + 2)
            {
                docs[0].InsertPage(docs[2], i);
            }
[VB.NET]
 Private Sub button1_Click(sender As Object, e As EventArgs)
	'pdf document list
	Dim files As [String]() = New [String]() {"..\PDFmerge0.pdf", "..\ PDFmerge1.pdf", "..\ PDFmerge2.pdf"}
	'open pdf documents            
	Dim docs As PdfDocument() = New PdfDocument(files.Length - 1) {}
	For i As Integer = 0 To files.Length - 1
		docs(i) = New PdfDocument(files(i))
	Next

	'append document
	docs(0).AppendPage(docs(1))

	'import PDF pages
	Dim i As Integer = 0
	While i < docs(2).Pages.Count
		docs(0).InsertPage(docs(2), i)
		i = i + 2
	End While

Step2: Draw page number in the first PDF file. In this step, you can set PDF page number margin by invoking the class Spire.Pdf.Graphics. PdfMargins. Then, Call the custom method DrawPageNumber(PdfPageCollection pages, PdfMargins margin, int startNumber, int pageCount) to add page number in the bottom of every page in the first PDF. Please see the detail code below:

[C#]
           //set PDF margin
            PdfUnitConvertor unitCvtr = new PdfUnitConvertor();
            PdfMargins margin = new PdfMargins();
            margin.Top = unitCvtr.ConvertUnits(2.54f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Bottom = margin.Top;
            margin.Left = unitCvtr.ConvertUnits(3.17f, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point);
            margin.Right = margin.Left;
            this.DrawPageNumber(docs[0].Pages, margin, 1, docs[0].Pages.Count);

          private void DrawPageNumber(PdfPageCollection pages, PdfMargins margin, int startNumber, int pageCount)
          {
            foreach (PdfPageBase page in pages)
            {
                page.Canvas.SetTransparency(0.5f);
                PdfBrush brush = PdfBrushes.Black;
                PdfPen pen = new PdfPen(brush, 0.75f);
                PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 9f, System.Drawing.FontStyle.Italic), true);
                PdfStringFormat format = new PdfStringFormat(PdfTextAlignment.Right);
                format.MeasureTrailingSpaces = true;
                float space = font.Height * 0.75f;
                float x = margin.Left;
                float width = page.Canvas.ClientSize.Width - margin.Left - margin.Right;
                float y = page.Canvas.ClientSize.Height - margin.Bottom + space;
                page.Canvas.DrawLine(pen, x, y, x + width, y);
                y = y + 1;
                String numberLabel
                    = String.Format("{0} of {1}", startNumber++, pageCount);
                page.Canvas.DrawString(numberLabel, font, brush, x + width, y, format);
                page.Canvas.SetTransparency(1);
            }
        }
[VB.NET]
       'set PDF margin
	Dim unitCvtr As New PdfUnitConvertor()
	Dim margin As New PdfMargins()
	margin.Top = unitCvtr.ConvertUnits(2.54F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
	margin.Bottom = margin.Top
	 margin.Left = unitCvtr.ConvertUnits(3.17F, PdfGraphicsUnit.Centimeter, PdfGraphicsUnit.Point)
	margin.Right = margin.Left
	Me.DrawPageNumber(docs(0).Pages, margin, 1, docs(0).Pages.Count)

       Private Sub DrawPageNumber(pages As PdfPageCollection, margin As PdfMargins, startNumber As Integer, pageCount As Integer)
	For Each page As PdfPageBase In pages
		page.Canvas.SetTransparency(0.5F)
		Dim brush As PdfBrush = PdfBrushes.Black
		Dim pen As New PdfPen(brush, 0.75F)
		Dim font As New PdfTrueTypeFont(New Font("Arial", 9F, System.Drawing.FontStyle.Italic), True)
		Dim format As New PdfStringFormat(PdfTextAlignment.Right)
		format.MeasureTrailingSpaces = True
		Dim space As Single = font.Height * 0.75F
		Dim x As Single = margin.Left
		Dim width As Single = page.Canvas.ClientSize.Width - margin.Left - margin.Right
		Dim y As Single = page.Canvas.ClientSize.Height - margin.Bottom + space
		page.Canvas.DrawLine(pen, x, y, x + width, y)
		y = y + 1
		Dim numberLabel As [String] = [String].Format("{0} of {1}", System.Math.Max(System.Threading.Interlocked.Increment(startNumber),startNumber - 1), pageCount)
		page.Canvas.DrawString(numberLabel, font, brush, x + width, y, format)
		page.Canvas.SetTransparency(1)
	Next
End Sub

The PDF merge code can be very long when you view it at first sight, actually, if you do not need to add page number in your merged PDF, steps two should be avoided. However, in many cases, page number brings great convenience for users to read PDF as well as print it. Spire.PDF for .NET can satisfy both your requirements of merging PDF files and adding page numbers in the merged PDF file.

Published in Document Operation

It's helpful to split a single PDF into several smaller ones in certain situations. For example, you can divide large contracts, reports, books, academic papers, or other documents into smaller pieces make them easy to review or reuse. In this article, you will learn how to split PDF into single-page PDFs and how to split PDF by page ranges in C# and VB.NET by 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

Split PDF into One-Page PDFs in C#, VB.NET

Spire.PDF offers the Split() method to divide a multi-page PDF document into multiple single-page files. The following are the detailed steps.

  • Create a PdfDcoument object.
  • Load a PDF document using PdfDocument.LoadFromFile() method.
  • Split the document into one-page PDFs using PdfDocument.Split(string destFilePattern, int startNumber) method.
  • C#
  • VB.NET
using System;
using Spire.Pdf;

namespace SplitPDFIntoIndividualPages
{
    class Program
    {
        static void Main(string[] args)
        {
            //Specify the input file path
            String inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";

            //Specify the output directory
            String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";

            //Create a PdfDocument object
            PdfDocument doc = new PdfDocument();

            //Load a PDF file
            doc.LoadFromFile(inputFile);

            //Split the PDF to one-page PDFs
            doc.Split(outputDirectory + "output-{0}.pdf", 1);
        }
    }
}

C#/VB.NET: Split PDF into Separate PDFs

Split PDF by Page Ranges in C#, VB.NET

No straightforward method is offered for splitting PDF documents by page ranges. To do so, we create two or more new PDF documents and import the page or page range from the source document into them. Here are the detailed steps.

  • Load the source PDF file while initialing the PdfDocument object.
  • Create two additional PdfDocument objects.
  • Import the first page from the source file to the first document using PdfDocument.InsertPage() method.
  • Import the remaining pages from the source file to the second document using PdfDocument.InsertPageRange() method.
  • Save the two documents as separate PDF files using PdfDocument.SaveToFile() method.
  • C#
  • VB.NET
using Spire.Pdf;
using System;

namespace SplitPdfByPageRanges
{
    class Program
    {
        static void Main(string[] args)
        {
            //Specify the input file path
            String inputFile = "C:\\Users\\Administrator\\Desktop\\Terms of Service.pdf";

            //Specify the output directory
            String outputDirectory = "C:\\Users\\Administrator\\Desktop\\Output\\";

            //Load the source PDF file while initialing the PdfDocument object
            PdfDocument sourceDoc = new PdfDocument(inputFile);

            //Create two additional PdfDocument objects
            PdfDocument newDoc_1 = new PdfDocument();
            PdfDocument newDoc_2 = new PdfDocument();

            //Insert the first page of source file to the first document
            newDoc_1.InsertPage(sourceDoc, 0);

            //Insert the rest pages of source file to the second document
            newDoc_2.InsertPageRange(sourceDoc, 1, sourceDoc.Pages.Count - 1);

            //Save the two documents as PDF files
            newDoc_1.SaveToFile(outputDirectory + "output-1.pdf");
            newDoc_2.SaveToFile(outputDirectory + "output-2.pdf");
        }
    }
}

C#/VB.NET: Split PDF into Separate PDFs

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.

Published in Document Operation
Page 3 of 3