PDF: Работа со страницами PDF документа
В этом разделе
Класс
PdfPageCollection представляет коллекцию страниц PDF документа. Коллекция страниц позволяет добавлять и вставлять новые страницы, изменять порядок и удалять существующие страницы.
Коллекцию страниц определенного PDF документа можно получить с помощью свойства
PdfDocument.Pages.
Вот C#/VB.NET код, который демонстрирует, как получить количество страниц в PDF документе:
/// <summary>
/// Returns the number of pages in PDF document.
/// </summary>
/// <param name="pdfFileName">The filename of PDF document.</param>
public static int GetPagesCount(string pdfFileName)
{
// open PDF document
using (Vintasoft.Imaging.Pdf.PdfDocument document =
new Vintasoft.Imaging.Pdf.PdfDocument(pdfFileName))
{
// get the number of pages
int pagesCount = document.Pages.Count;
// return number of pages
return pagesCount;
}
}
''' <summary>
''' Returns the number of pages in PDF document.
''' </summary>
''' <param name="pdfFileName">The filename of PDF document.</param>
Public Shared Function GetPagesCount(pdfFileName As String) As Integer
' open PDF document
Using document As New Vintasoft.Imaging.Pdf.PdfDocument(pdfFileName)
' get the number of pages
Dim pagesCount As Integer = document.Pages.Count
' return number of pages
Return pagesCount
End Using
End Function
Добавление/вставка PDF страниц
В PDF документ можно добавить/вставить новую страницу или существующую страницу исходного/другого документа.
При копировании страницы из одного PDF документа в другой будут также скопированы все объекты, используемые этой страницей.
Чтобы добавить страницу в PDF документ, необходимо сделать следующее:
- Создать или открыть PDF документ
- Получить коллекцию страниц PDF документа
- Добавить PDF страницу в коллекцию страниц PDF документа
- Сохранить изменения
Вот C#/VB.NET код, который демонстрирует, как добавить пустую страницу в PDF документ:
/// <summary>
/// Adds a new empty page into PDF document.
/// </summary>
/// <param name="pdfFileName">The filename of PDF document.</param>
/// <param name="pageSize">The size of page.</param>
public static void AddEmptyPageToPdfDocument(string pdfFileName, System.Drawing.SizeF pageSize)
{
// open PDF document
using (Vintasoft.Imaging.Pdf.PdfDocument document =
new Vintasoft.Imaging.Pdf.PdfDocument(pdfFileName))
{
// get the collection of pages of PDF document
Vintasoft.Imaging.Pdf.Tree.PdfPageCollection pages = document.Pages;
// add an empty page into collection of pages
pages.Add(pageSize);
// save changes to a file
document.SaveChanges();
}
}
''' <summary>
''' Adds a new empty page into PDF document.
''' </summary>
''' <param name="pdfFileName">The filename of PDF document.</param>
''' <param name="pageSize">The size of page.</param>
Public Shared Sub AddEmptyPageToPdfDocument(pdfFileName As String, pageSize As System.Drawing.SizeF)
' open PDF document
Using document As New Vintasoft.Imaging.Pdf.PdfDocument(pdfFileName)
' get the collection of pages of PDF document
Dim pages As Vintasoft.Imaging.Pdf.Tree.PdfPageCollection = document.Pages
' add an empty page into collection of pages
pages.Add(pageSize)
' save changes to a file
document.SaveChanges()
End Using
End Sub
Вот C#/VB.NET код, который демонстрирует, как добавить в PDF документ новую image-only страницу:
/// <summary>
/// Adds new image-only PDF page into a PDF document.
/// </summary>
/// <param name="pdfFileName">The filename of PDF document.</param>
/// <param name="image">The image of the page.</param>
public static void AddImageOnlyPdfPageToPdfDocument(
string pdfFileName,
Vintasoft.Imaging.VintasoftImage image)
{
// open PDF document
using (Vintasoft.Imaging.Pdf.PdfDocument document =
new Vintasoft.Imaging.Pdf.PdfDocument(pdfFileName))
{
// get the collection of pages of PDF document
Vintasoft.Imaging.Pdf.Tree.PdfPageCollection pages = document.Pages;
// add page with specified image into collection of pages
pages.Add(image);
// save changes to a file
document.SaveChanges();
}
}
''' <summary>
''' Adds new image-only PDF page into a PDF document.
''' </summary>
''' <param name="pdfFileName">The filename of PDF document.</param>
''' <param name="image">The image of the page.</param>
Public Shared Sub AddImageOnlyPdfPageToPdfDocument(pdfFileName As String, image As Vintasoft.Imaging.VintasoftImage)
' open PDF document
Using document As New Vintasoft.Imaging.Pdf.PdfDocument(pdfFileName)
' get the collection of pages of PDF document
Dim pages As Vintasoft.Imaging.Pdf.Tree.PdfPageCollection = document.Pages
' add page with specified image into collection of pages
pages.Add(image)
' save changes to a file
document.SaveChanges()
End Using
End Sub
Вот C#/VB.NET код, который демонстрирует, как скопировать первую страницу PDF документа в конец того же PDF документа:
/// <summary>
/// Copies the first page of PDF document to the end of PDF document.
/// </summary>
/// <param name="pdfFileName">The filename of PDF document.</param>
public static void CopyFirstPdfPageToEndOfPdfDocument(string pdfFileName)
{
// open PDF document
using (Vintasoft.Imaging.Pdf.PdfDocument document =
new Vintasoft.Imaging.Pdf.PdfDocument(pdfFileName))
{
// get the collection of pages of PDF document
Vintasoft.Imaging.Pdf.Tree.PdfPageCollection pages = document.Pages;
// add first page to the end of PDF document
pages.Add(pages[0]);
// save changes to a file
document.SaveChanges();
}
}
''' <summary>
''' Copies the first page of PDF document to the end of PDF document.
''' </summary>
''' <param name="pdfFileName">The filename of PDF document.</param>
Public Shared Sub CopyFirstPdfPageToEndOfPdfDocument(pdfFileName As String)
' open PDF document
Using document As New Vintasoft.Imaging.Pdf.PdfDocument(pdfFileName)
' get the collection of pages of PDF document
Dim pages As Vintasoft.Imaging.Pdf.Tree.PdfPageCollection = document.Pages
' add first page to the end of PDF document
pages.Add(pages(0))
' save changes to a file
document.SaveChanges()
End Using
End Sub
Вот C#/VB.NET код, который демонстрирует, как скопировать все страницы PDF документа в конец другого PDF документа:
/// <summary>
/// Copies all pages of source PDF document to the end of destination PDF document.
/// </summary>
/// <param name="srcPdfFileName">The filename of source PDF document.</param>
/// <param name="destPdfFileName">The filename of destination PDF document.</param>
public static void CopyPagesFromOnePdfDocumentToAnother(string srcPdfFileName, string destPdfFileName)
{
// open source PDF document
using (Vintasoft.Imaging.Pdf.PdfDocument srcDocument =
new Vintasoft.Imaging.Pdf.PdfDocument(srcPdfFileName))
{
// open destination PDF document
using (Vintasoft.Imaging.Pdf.PdfDocument destDocument =
new Vintasoft.Imaging.Pdf.PdfDocument(destPdfFileName))
{
// get pages of source PDF document as array
Vintasoft.Imaging.Pdf.Tree.PdfPage[] srcDocumentPages = srcDocument.Pages.ToArray();
// append the array of PDF pages to the destination PDF document
destDocument.Pages.AddRange(srcDocumentPages);
// save changes to a file
destDocument.SaveChanges();
}
}
}
''' <summary>
''' Copies all pages of source PDF document to the end of destination PDF document.
''' </summary>
''' <param name="srcPdfFileName">The filename of source PDF document.</param>
''' <param name="destPdfFileName">The filename of destination PDF document.</param>
Public Shared Sub CopyPagesFromOnePdfDocumentToAnother(srcPdfFileName As String, destPdfFileName As String)
' open source PDF document
Using srcDocument As New Vintasoft.Imaging.Pdf.PdfDocument(srcPdfFileName)
' open destination PDF document
Using destDocument As New Vintasoft.Imaging.Pdf.PdfDocument(destPdfFileName)
' get pages of source PDF document as array
Dim srcDocumentPages As Vintasoft.Imaging.Pdf.Tree.PdfPage() = srcDocument.Pages.ToArray()
' append the array of PDF pages to the destination PDF document
destDocument.Pages.AddRange(srcDocumentPages)
' save changes to a file
destDocument.SaveChanges()
End Using
End Using
End Sub
Добавление/вставка image-only PDF страниц
В PDF документ можно добавить/вставить новую image-only PDF страницу.
Вот C#/VB.NET код, который демонстрирует, как добавлять изображения в PDF документ, используя класс
PdfDocument:
public static void AddImagesToPdf(string pdfFilename,
Vintasoft.Imaging.ImageCollection images)
{
using (Vintasoft.Imaging.Pdf.PdfDocument document =
new Vintasoft.Imaging.Pdf.PdfDocument(pdfFilename))
{
// add images to PDF document using LZW compression
for (int i = 0; i < images.Count; i++)
document.Pages.Add(images[i], Vintasoft.Imaging.Pdf.PdfCompression.Lzw);
// save document changes
document.SaveChanges();
}
}
Public Shared Sub AddImagesToPdf(pdfFilename As String, images As Vintasoft.Imaging.ImageCollection)
Using document As New Vintasoft.Imaging.Pdf.PdfDocument(pdfFilename)
' add images to PDF document using LZW compression
For i As Integer = 0 To images.Count - 1
document.Pages.Add(images(i), Vintasoft.Imaging.Pdf.PdfCompression.Lzw)
Next
' save document changes
document.SaveChanges()
End Using
End Sub
Вот C#/VB.NET код, который демонстрирует, как добавлять изображения в PDF документ с помощью класса
PdfEncoder:
public static void AddImagesToPdf(string pdfFilename,
Vintasoft.Imaging.ImageCollection images)
{
using (Vintasoft.Imaging.Codecs.Encoders.PdfEncoder encoder =
new Vintasoft.Imaging.Codecs.Encoders.PdfEncoder(false))
{
// use LZW compression
encoder.Settings.Compression = Vintasoft.Imaging.Codecs.Encoders.PdfImageCompression.Lzw;
// add images to PDF document
using (System.IO.Stream stream = new System.IO.FileStream(
pdfFilename, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite))
{
encoder.SaveImages(images, stream);
}
}
}
Public Shared Sub AddImagesToPdf(pdfFilename As String, images As Vintasoft.Imaging.ImageCollection)
Using encoder As New Vintasoft.Imaging.Codecs.Encoders.PdfEncoder(False)
' use LZW compression
encoder.Settings.Compression = Vintasoft.Imaging.Codecs.Encoders.PdfImageCompression.Lzw
' add images to PDF document
Using stream As System.IO.Stream = New System.IO.FileStream(pdfFilename, System.IO.FileMode.Open, System.IO.FileAccess.ReadWrite)
encoder.SaveImages(images, stream)
End Using
End Using
End Sub
Изменение порядка PDF страниц
Класс
PdfPageCollection - это коллекция, которая предоставляет возможность переупорядочивать элементы коллекции - страницы PDF документа.
Чтобы изменить порядок страниц в PDF документе, необходимо сделать следующее:
- Открыть PDF документ
- Получить коллекцию страниц PDF документа
- Пересортировать страницы
- Сохранить изменения
Вот C#/VB.NET код, который демонстрирует, как изменить порядок страниц в PDF документе:
/// <summary>
/// Swaps the first and the last pages of PDF document.
/// </summary>
/// <param name="pdfFileName">The filename of PDF document.</param>
public static void SwapPages(string pdfFileName)
{
// open PDF documnet
using (Vintasoft.Imaging.Pdf.PdfDocument document =
new Vintasoft.Imaging.Pdf.PdfDocument(pdfFileName))
{
// get the collection of pages of PDF document
Vintasoft.Imaging.Pdf.Tree.PdfPageCollection pages = document.Pages;
// get the page count
int pagesCount = pages.Count;
// swap the first and the last pages
pages.Swap(0, pagesCount - 1);
// save changes to a file
document.SaveChanges();
}
}
''' <summary>
''' Swaps the first and the last pages of PDF document.
''' </summary>
''' <param name="pdfFileName">The filename of PDF document.</param>
Public Shared Sub SwapPages(pdfFileName As String)
' open PDF documnet
Using document As New Vintasoft.Imaging.Pdf.PdfDocument(pdfFileName)
' get the collection of pages of PDF document
Dim pages As Vintasoft.Imaging.Pdf.Tree.PdfPageCollection = document.Pages
' get the page count
Dim pagesCount As Integer = pages.Count
' swap the first and the last pages
pages.Swap(0, pagesCount - 1)
' save changes to a file
document.SaveChanges()
End Using
End Sub
Удаление PDF страниц
Страница в PDF документе может быть удалена виртуально или физически. При виртуальном удалении страница удаляется из списка страниц, но ее данные остаются нетронутыми. При физическом удалении страница полностью удаляется вместе со всеми ее данными.
Чтобы выполнить виртуальное удаление PDF страниц, необходимо сделать следующее:
- Открыть PDF документ
- Получить коллекцию страниц PDF документа
- Удалить одну или несколько страниц
- Сохранить изменения
Вот C#/VB.NET код, который демонстрирует, как виртуально удалить страницу из PDF документа:
public void VirtuallyRemovePageFromPDFDocument(string filename, int pageIndex)
{
// open PDF document
using (Vintasoft.Imaging.Pdf.PdfDocument document =
new Vintasoft.Imaging.Pdf.PdfDocument(filename))
{
// remove page at specified index
document.Pages.RemoveAt(pageIndex);
// save changes
document.SaveChanges();
}
}
Public Sub VirtuallyRemovePageFromPDFDocument(filename As String, pageIndex As Integer)
' open PDF document
Using document As New Vintasoft.Imaging.Pdf.PdfDocument(filename)
' remove page at specified index
document.Pages.RemoveAt(pageIndex)
' save changes
document.SaveChanges()
End Using
End Sub
Чтобы выполнить физическое удаление PDF страницы, необходимо сделать следующее:
- Открыть PDF документ
- Получить коллекцию страниц PDF документа
- Удалить одну или несколько страниц
- Упаковать PDF документ
Вот C#/VB.NET код, который демонстрирует, как физически удалить страницу из PDF документа:
public void PhysicallyRemovePageFromPDFDocument(string filename, int pageIndex)
{
// open PDF document
using (Vintasoft.Imaging.Pdf.PdfDocument document =
new Vintasoft.Imaging.Pdf.PdfDocument(filename))
{
// remove page at specified index
document.Pages.RemoveAt(pageIndex);
// pack document
document.Pack();
}
}
Public Sub PhysicallyRemovePageFromPDFDocument(filename As String, pageIndex As Integer)
' open PDF document
Using document As New Vintasoft.Imaging.Pdf.PdfDocument(filename)
' remove page at specified index
document.Pages.RemoveAt(pageIndex)
' pack document
document.Pack()
End Using
End Sub