C# / VB.NET合并PDF指定页

  在前面的文章中,我们已经知道如何合并、拆分多个PDF文件,在这篇文章中的合并、拆分PDF文档主要是以方便文档管理的目的来操作文档,在文档查阅、管理及存储上很方便实用。但是我们如果想要合并多个文档中的部分文档页的内容,该如何来做呢?可以参考接下来将要介绍的合并方法。

  PS: 本篇文章是对Free Spire.PDF 的合并功能的进一步介绍,即如何合并多个PDF文档中的指定页(指定单页、指定多页)为一个新文档

  使用工具:Free Spire.PDF for .NET

  提示:下载安装该组件后,注意在项目程序中添加引用Spire.PDF.dll文件

  代码细节可参考以下主要代码段:

  //初始化数组,数组元素为需要合并的PDF文档

  string[] files = { "sample1.pdf", "sample2.pdf" };

  PdfDocument[] docs = new PdfDocument[files.Length];

  //遍历PDF文档

  for (int i = 0; i < files.Length; i++)

  {

  docs[i] = new PdfDocument();

  docs[i].LoadFromFile(files[i]);

  }

  //创建一个新的PDF文档并插入从原文档选取的指定页

  PdfDocument doc = new PdfDocument();

  doc.InsertPage(docs[0], 0);//指定单页(文档1的第1页)

  doc.InsertPageRange(docs[1], 0, 1);//指定多页 (文档2的第1页和第2页)

  //保存并命名合并后的文档,同时运行文档

  doc.SaveToFile("Result.pdf");

  Process.Start("Result.pdf");

  复制代码

  合并前:

C# / VB.NET合并PDF指定页

  合并后:

C# / VB.NET合并PDF指定页

  全部代码

  C#

  using Spire.Pdf;

  using System.Diagnostics;

  namespace MergeSelectedPDFpages

  {

  class Program

  {

  static void Main(string[] args)

  {

  string[] files = { "sample1.pdf", "sample2.pdf" };

  PdfDocument[] docs = new PdfDocument[files.Length];

  for (int i = 0; i < files.Length; i++)

  {

  docs[i] = new PdfDocument();

  docs[i].LoadFromFile(files[i]);

  }

  PdfDocument doc = new PdfDocument();

  doc.InsertPage(docs[0], 0);

  doc.InsertPageRange(docs[1], 0, 1);

  doc.SaveToFile("Result.pdf");

  Process.Start("Result.pdf");

  }

  }

  }

  复制代码

  VB.NET

  Imports Spire.Pdf

  Imports System.Diagnostics

  Namespace MergeSelectedPDFpages

  Class Program

  Private Shared Sub Main(ByVal args() As String)

  Dim files() As String = New String() {"sample1.pdf", "sample2.pdf"}

  Dim docs() As PdfDocument = New PdfDocument((files.Length) - 1) {}

  Dim i As Integer = 0

  Do While (i < files.Length)

  docs(i) = New PdfDocument

  docs(i).LoadFromFile(files(i))

  i = (i + 1)

  Loop

  Dim doc As PdfDocument = New PdfDocument

  doc.InsertPage(docs(0), 0)

  doc.InsertPageRange(docs(1), 0, 1)

  doc.SaveToFile("Result.pdf")

  Process.Start("Result.pdf")

  End Sub

  End Class

  End Namespace

  复制代码(编辑:雷林鹏 来源:网络)

原文地址:https://www.cnblogs.com/pengpeng1208/p/9353210.html