C#/VB.NET: Merge Multiple PDF Files into a Single PDF

Merging multiple PDF files into a single file can facilitate document management, distribution, and printing. After merging, you only need to work with one file instead of multiple files. This article will explain how to merge multiple PDF files into a single PDF in C# and VB.NET.

This article includes the following topics:

  • Merge Multiple PDF Files into a Single PDF
  • Merge Specific Pages of Multiple PDF Files into a Single PDF
  • Merge PDF Files with Different Page Sizes into One PDF with the Same Page Size
  • Merge PDF Files from Streams

Installation

In order to merge PDF files, this article uses a third-party library called Spire.PDF for .NET.

You can install Spire.PDF for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package Spire.PDF

Alternatively, you can also download the API from the official website and extract the package, then add the DLL files under the BIN folder to your project as references.

Merge Multiple PDF Files into a Single PDF in C# and VB.NET

Spire.PDF offers a static method – PdfDocument.MergeFiles(string[] inputFiles) which allows you to merge multiple PDF files specified by the paths in a string array to a single PDF. The following are the detailed steps:

  • Put the PDF files’ paths into a string array.
  • Merge the PDF files specified by the paths in the string array into a single PDF using PdfDocument.MergeFiles(string[] inputFiles) method.
  • Save the merged PDF to file using PdfDocumentBase.Save(string fileName) method.

C#

using Spire.Pdf;

namespace MergePdfFiles
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Put the PDF files' paths into a string array
            string[] files = new string[] { "File1.pdf", "File2.pdf", "File3.pdf" };

            //Merge the PDF files specified by the paths into a single PDF
            PdfDocumentBase pdf = PdfDocument.MergeFiles(files);
            //Save the result PDF file
            pdf.Save("Merge.pdf");
        }
    }
}

VB.NET

Imports Spire.Pdf

Namespace MergePdfFiles
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Put the PDF files' paths into a string array
            Dim files = New String() {"File1.pdf", "File2.pdf", "File3.pdf"}

            'Merge the PDF files specified by the paths into a single PDF
            Dim pdf As PdfDocumentBase = PdfDocument.MergeFiles(files)
            'Save the result PDF file
            pdf.Save("Merge.pdf")
        End Sub
    End Class
End Namespace

Merge Specific Pages of Multiple PDF Files into a Single PDF in C# and VB.NET

You can merge a specific page or a range of pages of multiple PDF files into a single PDF file using PdfDocument.InsertPage(PdfDocument ldDoc, int pageIndex) or PdfDocument.insertPageRange(PdfDocument ldDoc, int startIndex, int endIndex) method. The following are the detailed steps:

  • Initialize an instance of PdfDocument class.
  • Load the first PDF file using PdfDocument.LoadFromFile(string fileName) method.
  • Initialize an instance of PdfDocument class.
  • Load the second PDF file using PdfDocument.LoadFromFile(string fileName) method.
  • Initialize an instance of PdfDocument class to create a new PDF file.
  • Import a specific page of the first PDF to the new PDF using PdfDocument.InsertPage(PdfDocument ldDoc, int pageIndex) method.
  • Import a range of pages of the second PDF to the new PDF using PdfDocument.insertPageRange(PdfDocument ldDoc, int startIndex, int endIndex) method.
  • Save the new PDF to file using PdfDocument.SaveToFile(string fileName) method.

C#

using Spire.Pdf;

namespace MergePdfPages
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of PdfDocument class
            PdfDocument pdf1 = new PdfDocument();
            //Load the first PDF file
            pdf1.LoadFromFile("File1.pdf");
            //Initialize an instance of PdfDocument class
            PdfDocument pdf2 = new PdfDocument();
            //Load the second PDF file
            pdf1.LoadFromFile("File2.pdf");

            //Initialize an instance of PdfDocument class to create a new PDF file
            PdfDocument newPdf = new PdfDocument();
            //Import the 1st page of the first PDF to the new PDF
            newPdf.InsertPage(pdf1, 0);
            //Import the 3rd and the 4th pages of the second PDF to the new PDF
            newPdf.InsertPageRange(pdf2, 2, 3);

            //Save the result PDF file
            newPdf.SaveToFile("MergePages.pdf");
        }
    }
}

VB.NET

Imports Spire.Pdf

Namespace MergePdfPages
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of PdfDocument class
            Dim pdf1 As PdfDocument = New PdfDocument()
            'Load the first PDF file
            pdf1.LoadFromFile("File1.pdf")
            'Initialize an instance of PdfDocument class
            Dim pdf2 As PdfDocument = New PdfDocument()
            'Load the second PDF file
            pdf1.LoadFromFile("File2.pdf")

            'Initialize an instance of PdfDocument class to create a new PDF file
            Dim newPdf As PdfDocument = New PdfDocument()
            'Import the 1st page of the first PDF to the new PDF
            newPdf.InsertPage(pdf1, 0)
            'Import the 3rd and the 4th pages of the second PDF to the new PDF
            newPdf.InsertPageRange(pdf2, 2, 3)

            'Save the result PDF file
            newPdf.SaveToFile("MergePages.pdf")
        End Sub
    End Class
End Namespace

Merge PDF Files with Different Page Sizes into One PDF with the Same Page Size in C# and VB.NET

You can merge PDF files with different page sizes into a single PDF with the same page size by creating a new PDF with a specific page size, then redrawing the page content of the original PDF files to the new PDF.

  • Put the PDF files’ paths into a string array.
  • Initialize an instance of PdfDocument class to create a new PDF file, set its page size and margins.
  • Iterate through the string array.
  • Initialize an instance of the PdfDocument class and load the PDF file specified by the path in the array using PdfDocument.LoadFromFile(string fileName) method.
  • Iterate through all pages in the PDF file.
  • Add pages to the new PDF using PdfDocument.Pages.Add() method.
  • Initialize an instance of PdfTextLayout class and then specify the text layout as one page to ensure the page content of the loaded PDF fit the page size of the new PDF.
  • Redraw the page content of the loaded PDF to the pages of the new PDF using PdfDocument.Pages[int].CreateTemplate().Draw(PdfPageBase page, PointF location, PdfTextLayout format) method.
  • Save the new PDF to file using PdfDocument.SaveToFile(string fileName) method.

C#

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

namespace MergePdfFiles
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Put the PDF files' paths into a string array
            string[] files = new string[] { "File1.pdf", "File2.pdf", "File3.pdf" };

            //Initialize an instance of PdfDocument class to create a new PDF file
            PdfDocument newPdf = new PdfDocument();
            //Set page size
            newPdf.PageSettings.Size = PdfPageSize.A4;
            //Remove page margins
            newPdf.PageSettings.Margins.All = 0;

            //Loop through the string array
            for (int i = 0; i < files.Length - 1; i++)
            {
                //Load the PDF file
                PdfDocument pdf = new PdfDocument();
                pdf.LoadFromFile(files[i]);
                //Iterate through all pages in the PDF
                for (int j = 0; j < pdf.Pages.Count; j++)
                {
                    //Add a page to the new PDF
                    PdfPageBase newPage = newPdf.Pages.Add();
                    //Specify text layout as 1 page to ensure the page content fit the page size of the new PDF
                    PdfTextLayout layout = new PdfTextLayout();
                    layout.Layout = PdfLayoutType.OnePage;
                    //Redraw the page content of the loaded PDF to the page of the new PDF
                    pdf.Pages[j].CreateTemplate().Draw(newPage, new System.Drawing.PointF(0, 0), layout);
                }
            }

            //Save the result PDF file
            newPdf.SaveToFile("MergePdfsWithDifferentPageSizes.pdf");
        }
    }
}

VB.NET

Imports Spire.Pdf
Imports Spire.Pdf.Graphics

Namespace MergePdfFiles
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Put the PDF files' paths into a string array
            Dim files = New String() {"File1.pdf", "File2.pdf", "File3.pdf"}

            'Initialize an instance of PdfDocument class to create a new PDF file
            Dim newPdf As PdfDocument = New PdfDocument()
            'Set page size
            newPdf.PageSettings.Size = PdfPageSize.A4
            'Remove page margins
            newPdf.PageSettings.Margins.All = 0

            'Loop through the string array
            For i = 0 To files.Length - 1 - 1
                'Load the PDF file
                Dim pdf As PdfDocument = New PdfDocument()
                pdf.LoadFromFile(files(i))
                'Iterate through all pages in the PDF
                For j As Integer = 0 To pdf.Pages.Count - 1
                    'Add a page to the new PDF
                    Dim newPage As PdfPageBase = newPdf.Pages.Add()
                    'Specify text layout as 1 page to ensure the page content fit the page size of the new PDF
                    Dim layout As PdfTextLayout = New PdfTextLayout()
                    layout.Layout = PdfLayoutType.OnePage
                    'Redraw the page content of the loaded PDF to the page of the new PDF
                    pdf.Pages(j).CreateTemplate().Draw(newPage, New Drawing.PointF(0, 0), layout)
                Next
            Next

            'Save the result PDF file
            newPdf.SaveToFile("MergePdfsWithDifferentPageSizes.pdf")
        End Sub
    End Class
End Namespace

Merge PDF Files from Streams in C# and VB.NET

To merge multiple PDF files from streams, you can use the PdfDocument.MergeFiles(Stream[] streams) method. The following are the detailed steps:

  • Read the PDF files into streams using File.OpenRead(string path) method.
  • Put the streams into a stream array.
  • Merge the PDF streams using PdfDocument.MergeFiles(Stream[] streams) method.
  • Save the result PDF to file using PdfDocumentBase.Save(string fileName) method. You can also save the PDF to stream by passing a Stream object to the PdfDocumentBase.Save() method.

C#

using Spire.Pdf;

namespace MergePdfFilesFromStreams
{
    internal class Program
    {
        static void Main(string[] args)
        {
            //Read the PDF files into streams
            Stream stream1 = File.OpenRead("File1.pdf");
            Stream stream2 = File.OpenRead("File2.pdf");
            Stream stream3 = File.OpenRead("File3.pdf");

            //Put the streams into a stream array
            Stream[] streams = { stream1, stream2, stream3};
            //Merge the pdf streams
            PdfDocumentBase pdf = PdfDocument.MergeFiles(streams);

            //Save the result PDF file
            pdf.Save("MergePdfsFromStreams.pdf");
        }
    }
}

VB.NET

Imports Spire.Pdf

Namespace MergePdfFilesFromStreams
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Read the PDF files into streams
            Dim stream1 As Stream = File.OpenRead("File1.pdf")
            Dim stream2 As Stream = File.OpenRead("File2.pdf")
            Dim stream3 As Stream = File.OpenRead("File3.pdf")

            'Put the streams into a stream array
            Dim streams = {stream1, stream2, stream3}
            'Merge the pdf streams
            Dim pdf As PdfDocumentBase = PdfDocument.MergeFiles(streams)

            'Save the result PDF file
            pdf.Save("MergePdfsFromStreams.pdf")
        End Sub
    End Class
End Namespace

Create Tagged PDF in Java

A tagged PDF is a PDF document in which each content element is labeled with a tag. These tags are invisible on the document pages, but they can help assistive technologies understand the structure of the document and thereby enabling people with disabilities to access the information in the document. A tagged PDF can also provide a high-quality reading experience to users using smart mobile devices because it can re-flow to adapt its presentation to different screen sizes. In this article, I will demonstrate how to create tagged PDF documents in Java.

Add Dependencies

To create tagged PDFs, this article uses Spire.PDF for Java. If you are using maven, you can install the jar of Spire.PDF for Java into your project by adding the following code to your project’s pom.xml file.

<repositories>   
    <repository>    
        <id>com.e-iceblue</id>   
        <name>e-iceblue</name>   
        <url>http://repo.e-iceblue.com/nexus/content/groups/public/</url>   
    </repository>   
</repositories>   
<dependencies>   
    <dependency>   
        <groupId> e-iceblue </groupId>   
        <artifactId>spire.pdf </artifactId>   
        <version>9.1.4</version>   
    </dependency>   
</dependencies>

If you are not using maven, you can download Spire.PDF for Java from this website, extract the package and then import the Spire.Pdf.jar under the lib folder into your project as a dependency.

Create Tagged PDF in Java

Spire.PDF provides the PdfTaggedContent class to generate tagged PDF documents. You can include various structural elements in a tagged PDF document, including heading, paragraph, figure, table, link, list, and many more.

The following are the main steps to create a tagged PDF with various structural elements using Java:

  • Initialize an instance of the PdfDocument class and add a page to it using PdfDocument.getPages().add() method.
  • Set the tab order of the page using PdfPageBase.setTabOrder(TabOrder) method.
  • Initialize an instance of the PdfTaggedContent class and pass the PdfDocument instance to the class constructor as a parameter.
  • Set the language and title of the document.
  • Add a document element which is the root element of a structure tree to the document using PdfTaggedContent.getStructureTreeRoot().appendChildElement() method.
  • Add a heading/paragraph/list/figure/table/ link element under the document element using PdfStructureElement.appendChildElement() method.
  • Add a start tag to indicate the beginning of the element using PdfStructureElement.beginMarkedContent() method.
  • Specify the element content and draw it onto the page.
  • Add an end tag to indicate the ending of the element using PdfStructureElement.endMarkedContent() method.
  • Save the result document to a PDF file using PdfDocument.saveToFile() method.
import com.spire.pdf.PdfDocument;
import com.spire.pdf.PdfPageBase;
import com.spire.pdf.PdfPageSize;
import com.spire.pdf.TabOrder;
import com.spire.pdf.annotations.PdfTextWebLink;
import com.spire.pdf.graphics.*;
import com.spire.pdf.interchange.taggedpdf.PdfStandardStructTypes;
import com.spire.pdf.interchange.taggedpdf.PdfStructureElement;
import com.spire.pdf.interchange.taggedpdf.PdfTaggedContent;
import com.spire.pdf.lists.PdfMarker;
import com.spire.pdf.lists.PdfUnorderedList;
import com.spire.pdf.lists.PdfUnorderedMarkerStyle;
import com.spire.pdf.tables.PdfTable;

import java.awt.*;
import java.awt.geom.Point2D;
import java.awt.geom.Rectangle2D;

public class CreateTaggedPDF {
    public static void main(String []args) throws Exception {
        //Initialize an instance of the PdfDocument class
        PdfDocument doc = new PdfDocument();

        //Add a page
        PdfPageBase page = doc.getPages().add(PdfPageSize.A4, new PdfMargins(20));

        //Set tab order
        page.setTabOrder(TabOrder.Structure);

        //Initialize an instance of the PdfTaggedContent class
        PdfTaggedContent taggedContent = new PdfTaggedContent(doc);

        //Set language and title
        taggedContent.setLanguage("en-US");
        taggedContent.setTitle("Tagged PDF");

        //Set PDF/UA-1 compliance
        taggedContent.setPdfUA1Identification();

        //Create font and brush
        PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Times New Roman", Font.PLAIN,14), true);
        PdfBrush brush = PdfBrushes.getBlack();

        //Add a document element which is the root element of a structure tree
        PdfStructureElement document = taggedContent.getStructureTreeRoot().appendChildElement(PdfStandardStructTypes.Document);

        //Add a heading element
        PdfStructureElement heading1 = document.appendChildElement(PdfStandardStructTypes.HeadingLevel1);
        heading1.beginMarkedContent(page);
        String headingText = "What Is Java?";
        page.getCanvas().drawString(headingText, font, brush, 10, 0);
        heading1.endMarkedContent(page);

        //Add a paragraph element
        PdfStructureElement paragraph = document.appendChildElement(PdfStandardStructTypes.Paragraph);
        paragraph.beginMarkedContent(page);
        String paragraphText = "Java is a computer programming language that was first released in 1995. It is owned by Oracle, and more than 3 billion devices run Java. It can be used for:";
        Rectangle2D rect = new Rectangle2D.Float(10, 30, (float)page.getCanvas().getClientSize().getWidth(), (float)page.getCanvas().getClientSize().getHeight());
        page.getCanvas().drawString(paragraphText, font, brush, rect);
        paragraph.endMarkedContent(page);

        //Add a list element
        PdfStructureElement listElement = document.appendChildElement(PdfStandardStructTypes.List);
        listElement.beginMarkedContent(page);
        String listContent = "Mobile applications (specially Android apps)\n"
                + "Desktop applications\n"
                + "Web applications\n"
                + "Web servers and application servers\n"
                + "Database connection\n"
                + "Games\n"
                + "And many more!";
        PdfMarker marker = new PdfMarker(PdfUnorderedMarkerStyle.Asterisk);
        PdfTrueTypeFont markerFont = new PdfTrueTypeFont(new Font("Times New Roman", Font.PLAIN,6), true);
        marker.setFont(markerFont);
        PdfUnorderedList list = new PdfUnorderedList(listContent);
        list.setFont(font);
        list.setIndent(2);
        list.setTextIndent(4);
        list.setBrush(brush);
        list.setMarker(marker);
        list.draw(page,  10, 70);
        listElement.endMarkedContent(page);

        //Add a figure element
        PdfStructureElement figure = document.appendChildElement(PdfStandardStructTypes.Figure);
        figure.beginMarkedContent(page);
        PdfImage image = PdfImage.fromFile("JavaLogo.png");
        page.getCanvas().drawImage(image, 10, 190);
        figure.endMarkedContent(page);

        //Add a table element
        PdfStructureElement table = document.appendChildElement(PdfStandardStructTypes.Table);
        table.beginMarkedContent(page);
        PdfTable pdfTable = new PdfTable();
        pdfTable.getStyle().getDefaultStyle().setFont(font);

        //Define data
        String[] data = {"Year; Product; Sales",
                "2020; Components; $20,000",
                "2021; Bikes; $6,300"};
        String[][] dataSource = new String[data.length][];
        for (int i = 0; i < data.length; i++) {
            dataSource[i] = data[i].split("[;]", -1);
        }
        //Set data as the table data
        pdfTable.setDataSource(dataSource);

        pdfTable.getStyle().setShowHeader(true);
        pdfTable.draw(page.getCanvas(), new Point2D.Float(10, 280), 270f);
        table.endMarkedContent(page);

        //Add a link element
        PdfStructureElement link = document.appendChildElement(PdfStandardStructTypes.Link);
        link.beginMarkedContent(page);
        PdfTextWebLink link2 = new PdfTextWebLink();
        link2.setText("www.google.com");
        link2.setUrl("https://www.google.com");
        link2.setFont(font);
        link2.setBrush(brush);
        link2.drawTextWebLink(page.getCanvas(), new Point2D.Float(10, 340));
        link.endMarkedContent(page);

        //Save the result document
        doc.saveToFile("CreateTaggedPdf.pdf");
    }
}
Create Tagged PDF in Java

C#/VB.NET: Insert or Read Tables in Word Documents

Tables are very useful for presenting data. They can show complex information to readers in a way that is easy to read and understand. When generating a Word document, you may need to insert a table to organize your data. In certain cases, you may also want to read data from an existing table in a Word document. In this article, I will demonstrate how to insert or read tables in Word documents using C# and VB.NET.

Installation

To create or read tables in Word documents, this article uses Free Spire.Doc for .NET. You can install Free Spire.Doc for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package FreeSpire.Doc

Alternatively, you can also download the DLL files of Free Spire.Doc for .NET from the official website, extract the package and then add the DLL files under the Bin folder to your project as references.

Create Table in Word Document in C# and VB.NET

You can use the Section.AddTable() method to add a table to a specific section of a Word document. The following are the detailed steps:

  • Initialize an instance of the Document class.
  • Add a section to the document using Document.AddSection() method.
  • Define the data for the header row and the remaining rows of the table and store them in a one-dimensional string array and a two-dimensional string array respectively.
  • Add a table to the section using Section.AddTable() method and specify the number of table rows and columns using Table.ResetCells(int, int) method.
  • Get the first row of the table through Table.Rows[int] property and set it as the header row through TableRow.IsHeader property.
  • Iterate through the one-dimensional string array, assign the data in the array to the header row and set text formatting.
  • Iterate through the two-dimensional string array, assign the data in the array to the remaining rows and set text formatting.
  • Save the result document using Document.SaveToFile() method.

C#

using System.Drawing;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace InsertTable
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document doc = new Document();

            //Add a section to the document
            Section section = doc.AddSection();

            //Set page margins for the section (top (1 in), bottom (1 in), left (1.25 in), right (1.25 in))
            section.PageSetup.Margins.Top = 72f;
            section.PageSetup.Margins.Bottom = 72f;
            section.PageSetup.Margins.Left = 90f;
            section.PageSetup.Margins.Right = 90f;

            //Add a paragraph to the section
            Paragraph para = section.AddParagraph();
            //Set text alignment
            para.Format.HorizontalAlignment = HorizontalAlignment.Center;
            //Add text to the paragraph
            TextRange txtRange = para.AppendText("Employee List");
            txtRange.CharacterFormat.FontName = "Calibri";
            txtRange.CharacterFormat.FontSize = 16;           
            txtRange.CharacterFormat.Bold = true;

            //Define table data
            string[] header = { "Employee#", "Name", "Department" };
            string[][] data =
                    {
                        new string[]{"93775", "John", "Finance"},
                        new string[]{"38295", "Jane", "IT"},
                        new string[]{"83864", "Brain", "Marketing"},
                        new string[]{"39801", "Sandra", "R&D"},
                };

            //Add a table to the section
            Table table = section.AddTable(true);
            //Specify the number of rows and columns for the table
            table.ResetCells(data.Length + 1, header.Length);

            //Set the first row as table header
            TableRow headerRow = table.Rows[0];
            headerRow.IsHeader = true;
            //Set the height and background color of the header row
            headerRow.Height = 23;
            headerRow.RowFormat.BackColor = Color.FromArgb(142, 170, 219);

            //Add data to the header row
            for (int i = 0; i < header.Length; i++)
            {
                //Add a paragraph to each cell of the header row
                para = headerRow.Cells[i].AddParagraph();
                //Set text alignment
                headerRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                para.Format.HorizontalAlignment = HorizontalAlignment.Center;
                //Add data to the paragraph and set text format
                txtRange = para.AppendText(header[i]);
                txtRange.CharacterFormat.FontName = "Calibri";
                txtRange.CharacterFormat.FontSize = 14;
                txtRange.CharacterFormat.TextColor = Color.White;
                txtRange.CharacterFormat.Bold = true;
            }

            //Add data to the remaining rows
            for (int r = 0; r < data.Length; r++)
            {
                TableRow dataRow = table.Rows[r + 1];
                dataRow.Height = 20;
                for (int c = 0; c < data[r].Length; c++)
                {
                    //Add a paragraph to each cell of the rest of the rows
                    para = dataRow.Cells[c].AddParagraph();
                    //Set text alignment
                    para.Format.HorizontalAlignment = HorizontalAlignment.Center;
                    dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
                    //Add data to the paragraph and set text format
                    txtRange = para.AppendText(data[r][c]);
                    txtRange.CharacterFormat.FontName = "Calibri";
                    txtRange.CharacterFormat.FontSize = 11;
                }
            }

            //Save the result document
            doc.SaveToFile("InsertTable.docx", FileFormat.Docx2013);
        }
    }
}

VB.NET

Imports System.Drawing
Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields

Namespace InsertTable
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim doc As Document = New Document()

            'Add a section to the document
            Dim section As Section = doc.AddSection()

            'Set page margins for the section (top (1 in), bottom (1 in), left (1.25 in), right (1.25 in))
            section.PageSetup.Margins.Top = 72F
            section.PageSetup.Margins.Bottom = 72F
            section.PageSetup.Margins.Left = 90F
            section.PageSetup.Margins.Right = 90F

            'Add a paragraph to the section
            Dim para As Paragraph = section.AddParagraph()
            'Set text alignment
            para.Format.HorizontalAlignment = HorizontalAlignment.Center
            'Add text to the paragraph
            Dim txtRange As TextRange = para.AppendText("Employee List")
            txtRange.CharacterFormat.FontName = "Calibri"
            txtRange.CharacterFormat.FontSize = 16
            txtRange.CharacterFormat.Bold = True

            'Define table data
            Dim header = {"Employee#", "Name", "Department"}
            Dim data = {New String() {"93775", "John", "Finance"}, New String() {"38295", "Jane", "IT"}, New String() {"83864", "Brain", "Marketing"}, New String() {"39801", "Sandra", "R&D"}}

            'Add a table to the section
            Dim table As Table = section.AddTable(True)
            'Specify the number of rows and columns for the table
            table.ResetCells(data.Length + 1, header.Length)

            'Set the first row as table header
            Dim headerRow As TableRow = table.Rows(0)
            headerRow.IsHeader = True
            'Set the height and background color of the header row
            headerRow.Height = 23
            headerRow.RowFormat.BackColor = Color.FromArgb(142, 170, 219)

            'Add data to the header row
            For i = 0 To header.Length - 1
                'Add a paragraph to each cell of the header row
                para = headerRow.Cells(i).AddParagraph()
                'Set text alignment
                headerRow.Cells(i).CellFormat.VerticalAlignment = VerticalAlignment.Middle
                para.Format.HorizontalAlignment = HorizontalAlignment.Center
                'Add data to the paragraph and set text format
                txtRange = para.AppendText(header(i))
                txtRange.CharacterFormat.FontName = "Calibri"
                txtRange.CharacterFormat.FontSize = 14
                txtRange.CharacterFormat.TextColor = Color.White
                txtRange.CharacterFormat.Bold = True
            Next

            'Add data to the remaining rows
            For r = 0 To data.Length - 1
                Dim dataRow As TableRow = table.Rows(r + 1)
                dataRow.Height = 20
                For c = 0 To data(r).Length - 1
                    'Add a paragraph to each cell of the rest of the rows
                    para = dataRow.Cells(c).AddParagraph()
                    'Set text alignment
                    para.Format.HorizontalAlignment = HorizontalAlignment.Center
                    dataRow.Cells(c).CellFormat.VerticalAlignment = VerticalAlignment.Middle
                    'Add data to the paragraph and set text format
                    txtRange = para.AppendText(data(r)(c))
                    txtRange.CharacterFormat.FontName = "Calibri"
                    txtRange.CharacterFormat.FontSize = 11
                Next
            Next

            'Save the result document
            doc.SaveToFile("InsertTable.docx", FileFormat.Docx2013)
        End Sub
    End Class
End Namespace
Insert Table in Word using C# and VB.NET

The above example explains how to create a table with a predefined number of rows and columns. Besides that, you can also create a table by dynamically adding rows and cells as shown in the following example.

C#

using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;

namespace DynamicTable
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document doc = new Document();

            //Add a section to the document
            Section section = doc.AddSection();

            //Set page margins for the section (top(1 in), bottom(1 in), left(1.25 in), right(1.25 in))
            section.PageSetup.Margins.Top = 72f;
            section.PageSetup.Margins.Bottom = 72f;
            section.PageSetup.Margins.Left = 90f;
            section.PageSetup.Margins.Right = 90f;

            //Add a table to the section
            Table table = section.AddTable();

            //Dynamically add rows and cells to the table
            TableRow row = table.AddRow();
            TableCell cell = row.AddCell();
            cell.SetCellWidth(200, CellWidthType.Point);
            TextRange txtRange = cell.AddParagraph().AppendText("Product");
            txtRange.CharacterFormat.FontSize = 13;
            txtRange.CharacterFormat.Bold = true;
            cell = row.AddCell();
            cell.SetCellWidth(200, CellWidthType.Point);
            txtRange = cell.AddParagraph().AppendText("Unit Price");
            txtRange.CharacterFormat.FontSize = 13;
            txtRange.CharacterFormat.Bold = true;

            row = table.AddRow(true, false);
            cell = row.AddCell();
            cell.SetCellWidth(200, CellWidthType.Point);
            cell.AddParagraph().AppendText("Monitor");
            cell = row.AddCell();
            cell.SetCellWidth(200, CellWidthType.Point);
            cell.AddParagraph().AppendText("$500");

            row = table.AddRow(true, false);
            cell = row.AddCell();
            cell.SetCellWidth(200, CellWidthType.Point);
            cell.AddParagraph().AppendText("Keyboard");
            cell = row.AddCell();
            cell.SetCellWidth(200, CellWidthType.Point);
            cell.AddParagraph().AppendText("$80");

            row = table.AddRow(true, false);
            cell = row.AddCell();
            cell.SetCellWidth(200, CellWidthType.Point);
            cell.AddParagraph().AppendText("CPU Coolers");
            cell = row.AddCell();
            cell.SetCellWidth(200, CellWidthType.Point);
            cell.AddParagraph().AppendText("$20");

            row = table.AddRow(true, false);
            cell = row.AddCell();
            cell.SetCellWidth(200, CellWidthType.Point);
            cell.AddParagraph().AppendText("Mice");
            cell = row.AddCell();
            cell.SetCellWidth(200, CellWidthType.Point);
            cell.AddParagraph().AppendText("$120");

            //Apply table style
            table.ApplyStyle(DefaultTableStyle.MediumGrid1Accent5);

            //Save the result document
            doc.SaveToFile("DynamicTable.docx", FileFormat.Docx2013);
        }
    }
}

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports Spire.Doc.Fields

Namespace DynamicTable
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim doc As Document = New Document()

            'Add a section to the document
            Dim section As Section = doc.AddSection()

            'Set page margins for the section (top(1 in), bottom(1 in), left(1.25 in), right(1.25 in))
            section.PageSetup.Margins.Top = 72F
            section.PageSetup.Margins.Bottom = 72F
            section.PageSetup.Margins.Left = 90F
            section.PageSetup.Margins.Right = 90F

            'Add a table to the section
            Dim table As Table = section.AddTable()

            'Dynamically add rows and cells to the table
            Dim row As TableRow = table.AddRow()
            Dim cell As TableCell = row.AddCell()
            cell.SetCellWidth(200, CellWidthType.Point)
            Dim txtRange As TextRange = cell.AddParagraph().AppendText("Product")
            txtRange.CharacterFormat.FontSize = 13
            txtRange.CharacterFormat.Bold = True
            cell = row.AddCell()
            cell.SetCellWidth(200, CellWidthType.Point)
            txtRange = cell.AddParagraph().AppendText("Unit Price")
            txtRange.CharacterFormat.FontSize = 13
            txtRange.CharacterFormat.Bold = True

            row = table.AddRow(True, False)
            cell = row.AddCell()
            cell.SetCellWidth(200, CellWidthType.Point)
            cell.AddParagraph().AppendText("Monitor")
            cell = row.AddCell()
            cell.SetCellWidth(200, CellWidthType.Point)
            cell.AddParagraph().AppendText("$500")

            row = table.AddRow(True, False)
            cell = row.AddCell()
            cell.SetCellWidth(200, CellWidthType.Point)
            cell.AddParagraph().AppendText("Keyboard")
            cell = row.AddCell()
            cell.SetCellWidth(200, CellWidthType.Point)
            cell.AddParagraph().AppendText("$80")

            row = table.AddRow(True, False)
            cell = row.AddCell()
            cell.SetCellWidth(200, CellWidthType.Point)
            cell.AddParagraph().AppendText("CPU Coolers")
            cell = row.AddCell()
            cell.SetCellWidth(200, CellWidthType.Point)
            cell.AddParagraph().AppendText("$20")

            row = table.AddRow(True, False)
            cell = row.AddCell()
            cell.SetCellWidth(200, CellWidthType.Point)
            cell.AddParagraph().AppendText("Mice")
            cell = row.AddCell()
            cell.SetCellWidth(200, CellWidthType.Point)
            cell.AddParagraph().AppendText("$120")

            'Apply table style
            table.ApplyStyle(DefaultTableStyle.MediumGrid1Accent5)

            'Save the result document
            doc.SaveToFile("DynamicTable.docx", FileFormat.Docx2013)
        End Sub
    End Class
End Namespace
Dynamically Create Table in Word using C# and VB.NET

Read Table in Word Document in C# and VB.NET

To read data from a table in a Word document, you need to iterate through all rows in the table, all cells in each row, then extract text from each cell. The following are the detailed steps:

  • Initialize an instance of the Document class.
  • Load a Word document using Document.LoadFromFile() method.
  • Get a specific section by its index through Document.Sections[int] property.
  • Get a specific table in the section by its index through Section.Tables[int] property.
  • Initialize an instance of the StringBuilder class.
  • Iterate through all rows in the table.
  • Iterate through all cells in each row.
  • Iterate through all paragraphs in each cell.
  • Get the text from each paragraph through Paragraph.Text property and save the result into the StringBuilder using StringBuilder.Append() method.
  • Write the text in the StringBuilder into a text file using File.WriteAllText() method.

C#

using Spire.Doc;
using Spire.Doc.Documents;
using System.IO;
using System.Text;

namespace ReadTable
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the Document class
            Document document = new Document();
            //Load a Word document
            document.LoadFromFile("InsertTable.docx");

            //Get the first section
            Section section = document.Sections[0];

            //Get the first table in the first section
            Table table = section.Tables[0] as Table;

            //Initialize an instance of the StringBuilder class
            StringBuilder sb = new StringBuilder();

            //Iterate through all rows in the table
            for (int i = 0; i < table.Rows.Count; i++)
            {
                TableRow row = table.Rows[i];
                //Iterate through all cells in each row
                for (int j = 0; j < row.Cells.Count; j++)
                {
                    TableCell cell = row.Cells[j];
                    //Iterate through all paragraphs in each cell
                    for (int p = 0; p < cell.Paragraphs.Count; p++)
                    {
                        //Extract text from each paragraph
                        Paragraph paragraph = cell.Paragraphs[p];
                        string text = paragraph.Text;
                        //Append the text to the StringBuilder
                        sb.Append(text + " | ");
                    }
                }
                sb.Append("\r\n");
            }

            File.WriteAllText("ReadTable.txt", sb.ToString());
        }
    }
}

VB.NET

Imports Spire.Doc
Imports Spire.Doc.Documents
Imports System.IO
Imports System.Text

Namespace ReadTable
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the Document class
            Dim document As Document = New Document()
            'Load a Word document
            document.LoadFromFile("InsertTable.docx")

            'Get the first section
            Dim section As Section = document.Sections(0)

            'Get the first table in the first section
            Dim table As Table = TryCast(section.Tables(0), Table)

            'Initialize an instance of the StringBuilder class
            Dim sb As StringBuilder = New StringBuilder()

            'Iterate through all rows in the table
            For i As Integer = 0 To table.Rows.Count - 1
                Dim row As TableRow = table.Rows(i)
                'Iterate through all cells in each row
                For j As Integer = 0 To row.Cells.Count - 1
                    Dim cell As TableCell = row.Cells(j)
                    'Iterate through all paragraphs in each cell
                    For p As Integer = 0 To cell.Paragraphs.Count - 1
                        'Extract text from each paragraph
                        Dim paragraph As Paragraph = cell.Paragraphs(p)
                        Dim text As String = paragraph.Text
                        'Append the text to the StringBuilder
                        sb.Append(text & " | ")
                    Next
                Next
                sb.Append(vbCrLf)
            Next

            Call File.WriteAllText("ReadTable.txt", sb.ToString())
        End Sub
    End Class
End Namespace
Read Table in Word using C# and VB.NET

C#/VB.NET: Change Page Orientation of PDF Documents

In certain cases, you may need to change the orientation of individual pages or all pages in a PDF document. For example, your PDF document is in portrait mode, but you want to change it to landscape in order to insert a wide table containing multiple columns of data. In this article, I will demonstrate how to change the page orientation of a PDF document using C# and VB.NET. It includes the following topics:

  • Change the Page Orientation of a New PDF Document
  • Change the Page Orientation of an Existing PDF Document

Installation

To change the page orientation of PDFs, this article uses a third-party library called Spire.PDF for .NET.

You can install Spire.PDF for .NET via NuGet by selecting Tools > NuGet Package Manager > Package Manager Console, and then executing the following command:

PM> Install-Package Spire.PDF

Alternatively, you can also download the API from the official website and extract the package, then add the DLL files under the BIN folder to your project as references.

Change the Page Orientation of a New PDF Document in C# and VB.NET

There are two types of page orientations: portrait (vertical) and landscape (horizontal). When a PDF document is created, it’s in portrait orientation by default. Spire.PDF enables you to change the page orientation of a new PDF document by using the PdfDocument.PageSettings.Orientation property. The detailed steps are as follows:

  • Initialize an instance of the PdfDocument class to create a new PDF document.
  • Specify the page orientation of the document as landscape by setting the PdfDocument.PageSettings.Orientation property as PdfPageOrientation.Landscape.
  • Add a page to the document using PdfDocument.Pages.Add() method.
  • Initialize an instance of the PdfTrueTypeFont class to create a font.
  • Draw some text to a specific location on the page with the specified font using PdfPageBase.Canvas.DrawString() method.
  • Save the result document using PdfDocument.SaveToFile() method.

C#

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

namespace ChangePageOrientationForNewPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the PdfDocument class
            PdfDocument pdf = new PdfDocument();
            //Set the page orientation of the PDF document as landscape
            pdf.PageSettings.Orientation = PdfPageOrientation.Landscape;

            //Add a page to the PDF document
            PdfPageBase page = pdf.Pages.Add();

            //Initialize an instance of the PdfTrueTypeFont class
            PdfTrueTypeFont font = new PdfTrueTypeFont(new Font("Arial", 11f), true);
            //Add some text to the page
            string s = "Proper page orientation can make a world of difference for your PDF documents. It can " +
                "improve the legibility of the text or make it readable in the first place. After all, it isn’t easy to read a document if your text displays sideways." +
                "Read on to learn how to change a PDF file’s orientation from landscape to portrait — or vice versa.";
            Rectangle rect = new Rectangle(0, 50, (int)page.GetClientSize().Width, (int)page.GetClientSize().Height);
            page.Canvas.DrawString(s, font, PdfBrushes.Black, rect);

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

VB.NET

Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing

Namespace ChangePageOrientationForNewPdf
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the PdfDocument class
            Dim pdf As PdfDocument = New PdfDocument()
            'Set the page orientation of the PDF document as landscape
            pdf.PageSettings.Orientation = PdfPageOrientation.Landscape

            'Add a page to the PDF document
            Dim page As PdfPageBase = pdf.Pages.Add()

            'Initialize an instance of the PdfTrueTypeFont class
            Dim font As PdfTrueTypeFont = New PdfTrueTypeFont(New Font("Arial", 11F), True)
            'Add some text to the page
            Dim s = "Proper page orientation can make a world of difference for your PDF documents. It can " & "improve the legibility of the text or make it readable in the first place. After all, it isn’t easy to read a document if your text displays sideways." & "Read on to learn how to change a PDF file’s orientation from landscape to portrait — or vice versa."
            Dim rect As Rectangle = New Rectangle(0, 50, CInt(page.GetClientSize().Width), CInt(page.GetClientSize().Height))
            page.Canvas.DrawString(s, font, PdfBrushes.Black, rect)

            'Save the result document
            pdf.SaveToFile("ChangePageOrientationForNewPdf.pdf")
        End Sub
    End Class
End Namespace

The result PDF in landscape orientation (11.69 x 8.26 in):

Change Page Orientation of New PDF in C# and VB.NET

Change the Page Orientation of an Existing PDF Document in C# and VB.NET

Changing the page orientation of an existing PDF document will be a little more complicated. To implement this task, you need to create a new PDF, add pages with the desired page orientation to it, then redraw the page contents of the existing PDF document to the new PDF document. The following are the detailed steps:

  • Initialize an instance of the PdfDocument class.
  • Load an existing PDF document using PdfDocument.LoadFromFile() method.
  • Initialize an instance of the PdfDocument class to create a new PDF document.
  • Iterate through all pages in the existing PDF document.
  • Add pages to the new PDF document, set the page size to the same as the pages of the existing PDF document and specify the page orientation using PdfDocument.Pages.Add(SizeF size, PdfMargins margins, PdfPageRotateAngle rotation, PdfPageOrientation orientation) method.
  • Redraw the contents on the pages of the existing PDF document to the pages of the new PDF document using PdfPageBase.CreateTemplate().Draw(PdfPageBase page, PointF location) method.
  • Save the result document using PdfDocument.SaveToFile() method.

C#

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

namespace ChangePageOrientationForExistingPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the PdfDocument instance
            PdfDocument pdf = new PdfDocument();
            //Load an existing PDF document
            pdf.LoadFromFile("Sample.pdf");

            //Initialize an instance of the PdfDocument instance to create a new PDF document
            PdfDocument newPdf = new PdfDocument();

            PdfPageBase newPage;
            PdfPageBase page;

            //Iterate through all pages in the existing PDF
            for (int i = 0; i < pdf.Pages.Count; i++)
            {
                page = pdf.Pages[i];
                //Add pages to the new PDF, set the page size to the same as the page size of the existing PDF and specify the page orientation as landscape
                newPage = newPdf.Pages.Add(new SizeF(page.Size.Width, page.Size.Height), new PdfMargins(0), PdfPageRotateAngle.RotateAngle0, PdfPageOrientation.Landscape);

                //Create templates based on the pages of the existing PDF and draw the templates on the pages of the new PDF
                page.CreateTemplate().Draw(newPage, new PointF(0, 0));
            }

            //Save the new PDF to file
            newPdf.SaveToFile("ChangePageOrientationForExistingPdf.pdf");
        }
    }
}

VB.NET

Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing

Namespace ChangePageOrientationForExistingPdf
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the PdfDocument instance
            Dim pdf As PdfDocument = New PdfDocument()
            'Load an existing PDF document
            pdf.LoadFromFile("Sample.pdf")

            'Initialize an instance of the PdfDocument instance to create a new PDF document
            Dim newPdf As PdfDocument = New PdfDocument()

            Dim newPage As PdfPageBase
            Dim page As PdfPageBase

            'Iterate through all pages in the existing PDF
            For i As Integer = 0 To pdf.Pages.Count - 1
                page = pdf.Pages(i)
                'Add pages to the new PDF, set the page size to the same as the page size of the existing PDF and specify the page orientation as landscape
                newPage = newPdf.Pages.Add(New SizeF(page.Size.Width, page.Size.Height), New PdfMargins(0), PdfPageRotateAngle.RotateAngle0, PdfPageOrientation.Landscape)

                'Create templates based on the pages of the existing PDF and draw the templates on the pages of the new PDF
                page.CreateTemplate().Draw(newPage, New PointF(0, 0))
            Next

            'Save the new PDF to file
            newPdf.SaveToFile("ChangePageOrientationForExistingPdf.pdf")
        End Sub
    End Class
End Namespace
Change Page Orientation of Existing PDF in C# and VB.NET

Occasionally, you may find the page content cannot be completely drawn on the page due to the changes in the page width or height after changing page orientation. This usually happens when you change the page orientation from landscape to portrait.

You can use the PdfTextLayout class to fit the content to the page, but be aware that the content will be scaled in order to fit the page. The following is the code for your reference:

C#

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

namespace ChangePageOrientationForExsitingPdf
{
    class Program
    {
        static void Main(string[] args)
        {
            //Initialize an instance of the PdfDocument instance
            PdfDocument pdf = new PdfDocument();
            //Load an existing PDF document
            pdf.LoadFromFile("Sample1.pdf");

            //Initialize an instance of the PdfDocument instance to create a new PDF document
            PdfDocument newPdf = new PdfDocument();

            PdfPageBase newPage;
            PdfPageBase page;

            //Iterate through all pages in the existing PDF
            for (int i = 0; i < pdf.Pages.Count; i++)
            {
                page = pdf.Pages[i];
                //Add pages to the new PDF, set the page size to the same as the page size of the existing PDF and specify the page orientation as portrait
                newPage = newPdf.Pages.Add(new SizeF(page.Size.Width, page.Size.Height), new PdfMargins(0), PdfPageRotateAngle.RotateAngle0, PdfPageOrientation.Portrait);

                //Set the text layout 
                PdfTextLayout format = new PdfTextLayout();
                //Set text layout break type
                format.Break = PdfLayoutBreakType.FitPage;
                //Set the text layout type as one page
                format.Layout = PdfLayoutType.OnePage;

                //Create templates based on the pages of the existing PDF and draw the templates on the pages of the new PDF with the specified layout
                page.CreateTemplate().Draw(newPage, new PointF(0, 0), format);
            }

            //Save the new PDF to file
            newPdf.SaveToFile("ChangePageOrientationForExistingPdf1.pdf");
        }
    }
}

VB.NET

Imports Spire.Pdf
Imports Spire.Pdf.Graphics
Imports System.Drawing

Namespace ChangePageOrientationForExsitingPdf
    Friend Class Program
        Private Shared Sub Main(ByVal args As String())
            'Initialize an instance of the PdfDocument instance
            Dim pdf As PdfDocument = New PdfDocument()
            'Load an existing PDF document
            pdf.LoadFromFile("Sample1.pdf")

            'Initialize an instance of the PdfDocument instance to create a new PDF document
            Dim newPdf As PdfDocument = New PdfDocument()

            Dim newPage As PdfPageBase
            Dim page As PdfPageBase

            'Iterate through all pages in the existing PDF
            For i As Integer = 0 To pdf.Pages.Count - 1
                page = pdf.Pages(i)
                'Add pages to the new PDF, set the page size to the same as the page size of the existing PDF and specify the page orientation as portrait
                newPage = newPdf.Pages.Add(New SizeF(page.Size.Width, page.Size.Height), New PdfMargins(0), PdfPageRotateAngle.RotateAngle0, PdfPageOrientation.Portrait)

                'Set the text layout 
                Dim format As PdfTextLayout = New PdfTextLayout()
                'Set text layout break type
                format.Break = PdfLayoutBreakType.FitPage
                'Set the text layout type as one page
                format.Layout = PdfLayoutType.OnePage

                'Create templates based on the pages of the existing PDF and draw the templates on the pages of the new PDF with the specified layout
                page.CreateTemplate().Draw(newPage, New PointF(0, 0), format)
            Next

            'Save the new PDF to file
            newPdf.SaveToFile("ChangePageOrientationForExistingPdf1.pdf")
        End Sub
    End Class
End Namespace

See Also

C# or VB.NET: Insert, Delete, Reorder, Rotate or Extract Pages in PDF

C#/VB.NET: Change Page Margins of Existing PDF Documents

Design a site like this with WordPress.com
Get started