将页面添加到PDF文档

Aspose.PDF for .NET API提供了使用C#或其他任何.NET语言处理PDF文档中页面的完全灵活性。它在PageCollection中维护PDF文档的所有页面,可以用于处理PDF页面。 Aspose.PDF for .NET允许您在文件的任何位置向PDF文档插入页面,以及将页面添加到PDF文件的末尾。 本节展示了如何使用C#向PDF添加页面。

在PDF文件中添加或插入页面

Aspose.PDF for .NET允许您在文件的任何位置向PDF文档插入页面,以及将页面添加到PDF文件的末尾。

以下代码片段也适用于Aspose.PDF.Drawing库。

在所需位置的PDF文件中插入空白页面

要在PDF文件中插入空白页面:

  1. 创建一个带有输入PDF文件的Document类对象。
  2. 调用PageCollection集合的Insert方法,并指定索引。
  3. 使用Save方法保存输出PDF。

以下代码片段展示了如何在PDF文件中插入页面。

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void InsertAnEmptyPage()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Pages();

    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "InsertEmptyPage.pdf"))
    {
       // Insert an empty page in a PDF
       document.Pages.Insert(2);
        // Save PDF document
       document.Save(dataDir + "InsertEmptyPage_out.pdf");
    }
}

在上面的示例中,我们使用默认参数添加了空白页面。如果您需要使页面大小与文档中的另一个页面相同,您应该添加几行代码:

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void InsertAnEmptyPageWithParameters()
{
    var page = document.Pages.Insert(2);
    //copy page parameters from page 1
    page.ArtBox = document.Pages[1].ArtBox;
    page.BleedBox = document.Pages[1].BleedBox;
    page.CropBox = document.Pages[1].CropBox;
    page.MediaBox = document.Pages[1].MediaBox;
    page.TrimBox = document.Pages[1].TrimBox;
}

在PDF文件末尾添加空白页面

有时,您希望确保文档以空白页面结束。此主题解释了如何在PDF文档末尾插入空白页面。

要在PDF文件末尾插入空白页面:

  1. 创建一个带有输入PDF文件的Document类对象。
  2. 调用PageCollection集合的Add方法,不带任何参数。
  3. 使用Save方法保存输出PDF。

以下代码片段展示了如何在PDF文件末尾插入空白页面。

// For complete examples and data files, visit https://github.com/aspose-pdf/Aspose.PDF-for-.NET
private static void InsertAnEmptyPageAtTheEnd()
{
    // The path to the documents directory
    var dataDir = RunExamples.GetDataDir_AsposePdf_Pages();
    
    // Open PDF document
    using (var document = new Aspose.Pdf.Document(dataDir + "InsertEmptyPageAtEnd.pdf"))
    {
        // Insert an empty page at the end of a PDF file
        document.Pages.Add();
        // Save PDF document
        document.Save(dataDir + "InsertEmptyPageAtEnd_out.pdf");
    }
}