欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

C# iText split PDF C# 拆分PDF

程序员文章站 2022-12-09 23:15:10
Nuget install iText7 using iText.Kernel.Pdf; using iText.Kernel.Utils;using System;using System.Collections.Generic; namespace ConsoleApp1{ public cla ......

 nuget install itext7

using itext.kernel.pdf;

using system.linq;
using system.text;
using system.threading.tasks; 
using system.configuration; 
using itext.kernel.utils;
using itext.kernel.pdf;
using system.io;
using system.web.ui;
using system.windows.forms; 

class program
    {      
        static void main(string[] args)
        {
            ultimateitextsplitpdf();
            console.readline();
        }

        static void ultimateitextsplitpdf()
        {
            string rawpdffile = @"d:\c\c\consoleapp1\ejatt.pdf";
            program objprovider = new program();
            objprovider.pdfsplitexample(rawpdffile);
        }      

        void pdfsplitexample(string rawpdffile)
        {
            if(!file.exists(rawpdffile))
            {
                return;
            }
            mcspdfsplitter mcspdfsplitterprovider;
            //generated physical split pdf files by getnextpdfwriter of mcspdfsplitter
            using (var pdfdoc = new pdfdocument(new pdfreader(rawpdffile)))
            {
                mcspdfsplitterprovider = new mcspdfsplitter(pdfdoc, rawpdffile);                 
                var splitpdfdocs = mcspdfsplitterprovider.splitbypagecount(1);
                foreach (var splitpdf in splitpdfdocs)
                {
                    splitpdf.close();
                }               
            }

            mcspdfsplitterprovider.splitpdfnameslist.foreach(x =>
            {
                if (file.exists(x))
                {
                    byte[] pdfbyte = file.readallbytes(x);
                    console.writeline($"before delete,name {x},length {pdfbyte.length}");
                    file.delete(x);
                }
            });
        }
}

 


using itext.kernel.utils;
using system;
using system.collections.generic;

namespace consoleapp1
{
public class mcspdfsplitter : pdfsplitter
{
private int _pagenumber;
private string _rawpdffile;
public list<string> splitpdfnameslist = new list<string>();
public mcspdfsplitter(pdfdocument pdfdocument, string rawpdffile) : base(pdfdocument)
{
_rawpdffile = rawpdffile;
}

protected override pdfwriter getnextpdfwriter(pagerange documentpagerange)
{
_pagenumber++;
string splitpdffilename = _rawpdffile.substring(0,_rawpdffile.lastindexof(".pdf"))+ _pagenumber+"split" + guid.newguid().tostring().replace("-", "") + ".pdf";
splitpdfnameslist.add(splitpdffilename);
return new pdfwriter(splitpdffilename);
}
}
}