iTextSharp: 从PDF文件中复制指定的页面到一个新的PDF文件


    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://*.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;
                foreach (var pageNumber in pageNumbers)
                {
                    document.SetPageSize(reader.GetPageSizeWithRotation(pageNumber));
                    document.NewPage();


                    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);
                    }
                }
            }
            catch (Exception e)
            {
                throw new Exception(e.Message);
            }
            finally
            {
                document.Close();
            }
            return memoryStream.ToArray();
        }

    }
上一篇:C# 将多个图片合成 pdf 及 多个pdf 合成 pdf 方案


下一篇:iTextSharp 生成pdf时 部分信息用中文等显示