且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

iTextSharp的修剪PDF文档的页面

更新时间:2023-02-12 20:17:08

而不是删除文档中的你其实就是创建一个新的文件,只导入您要保留的网页页面。下面是一个完整的工作的WinForms应用程序,并认为(目标定位iTextSharp的5.1.1.0)。最后一个参数的函数 removePagesFromPdf 是网页保持一个数组。

Instead of deleting pages in a document what you actually do is create a new document and only import the pages that you want to keep. Below is a full working WinForms app that does that (targetting iTextSharp 5.1.1.0). The last parameter to the function removePagesFromPdf is an array of pages to keep.

以下作品中的code关闭物理文件,但会很容易地转换为基于流的东西,这样你就不必写入磁盘,如果你不想。

The code below works off of physical files but would be very easy to convert to something based on streams so that you don't have to write to disk if you don't want to.

using System;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Windows.Forms;
using iTextSharp.text.pdf;
using iTextSharp.text;


namespace Full_Profile1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            //The files that we are working with
            string sourceFolder = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            string sourceFile = Path.Combine(sourceFolder, "Test.pdf");
            string destFile = Path.Combine(sourceFolder, "TestOutput.pdf");

            //Remove all pages except 1,2,3,4 and 6
            removePagesFromPdf(sourceFile, destFile, 1, 2, 3, 4, 6);
            this.Close();
        }
        public void removePagesFromPdf(String sourceFile, String destinationFile, params int[] pagesToKeep)
        {
            //Used to pull individual pages from our source
            PdfReader r = new PdfReader(sourceFile);
            //Create our destination file
            using (FileStream fs = new FileStream(destinationFile, FileMode.Create, FileAccess.Write, FileShare.None))
            {
                using (Document doc = new Document())
                {
                    using (PdfWriter w = PdfWriter.GetInstance(doc, fs))
                    {
                        //Open the desitination for writing
                        doc.Open();
                        //Loop through each page that we want to keep
                        foreach (int page in pagesToKeep)
                        {
                            //Add a new blank page to destination document
                            doc.NewPage();
                            //Extract the given page from our reader and add it directly to the destination PDF
                            w.DirectContent.AddTemplate(w.GetImportedPage(r, page), 0, 0);
                        }
                        //Close our document
                        doc.Close();
                    }
                }
            }
        }
    }
}