iTextSharp: 从PDF文件中复制指定的页面到一个新的PDF文件
看官方文档,已经停止更新了,进入了维护阶段,推荐使用iText7。 https://github.com/itext/itext7-dotnet
使用的版本为
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="BouncyCastle" version="1.8.6.1" targetFramework="net48" />
<package id="iTextSharp" version="5.5.13.2" targetFramework="net48" />
<package id="itextsharp.xmlworker" version="5.5.13.2" targetFramework="net48" />
</packages>
代码示例,测试文件请自己准备:
class Program
{
static void Main(string[] args)
{
FileStream fileStream = new FileStream(@"C:\Data\pdftest.pdf", FileMode.Open, FileAccess.Read);
var fileBytes = CopyPagesFromPDF(fileStream, new List<int> { 2, 10, 8 });
FileStream destFileStream = new FileStream(@"C:\Data\pdfNew.pdf", FileMode.Create, FileAccess.ReadWrite);
destFileStream.Write(fileBytes, 0, fileBytes.Length);
destFileStream.Flush();
destFileStream.Close();
}
//https://stackoverflow.com/questions/4124106/add-a-page-to-pdf-document-using-itextsharp
private static byte[] CopyPagesFromPDF(Stream sourcePDFFileStream, List<int> pageNumbers)
{
if (pageNumbers == null || !pageNumbers.Any())
throw new ArgumentNullException("pageNumbers is null or empty");
pageNumbers.Sort();
if (pageNumbers.First() < 1)
throw new ArgumentException("the minum pageNumbers can't less than 0.");
// we create a reader for the document
PdfReader reader = new PdfReader(sourcePDFFileStream);
if (pageNumbers.Last() > reader.NumberOfPages)
throw new ArgumentException("the maxium pageNumbers can't great than max pageNumber");
MemoryStream memoryStream = new MemoryStream();
//Step 1: Create a Docuement-Object
Document document = new Document();
try
{
//Step 2: we create a writer that listens to the document
PdfWriter writer = PdfWriter.GetInstance(document, memoryStream);
//Step 3: Open the document
document.Open();
PdfContentByte cb = writer.DirectContent;
int currPageNumber = 1;
foreach (var pageNumber in pageNumbers)
{
document.SetPageSize(reader.GetPageSizeWithRotation(pageNumber));
document.NewPage();
document.PageCount = currPageNumber++;
PdfImportedPage page = writer.GetImportedPage(reader, pageNumber);
int rotation = reader.GetPageRotation(pageNumber);
if (rotation == 90 || rotation == 270)
{
cb.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(pageNumber).Height);
}
else
{
cb.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
}
}
writer.Close();
}
catch (Exception e)
{
throw new Exception(e.Message);
}
finally
{
document.Close();
}
return memoryStream.ToArray();
}
}