split PDF into multiple files in C#

2020-06-14 07:01发布

We have a C# Windows service that currently processes all the PDFs by reading the 2D barcode on the PDF using a 3rd party component and then updates the database and stores the document in the Document repository.

Is there a way I can cut the files after reading the barcode and store it as another document?

For example if there is a 10 page document, it should split into 10 different files.

Thanks.

标签: c# pdf
7条回答
劫难
2楼-- · 2020-06-14 07:04
    public  void SplitPDFByBookMark(string fileName)
    {
        string sInFile = fileName;
        var pdfReader = new PdfReader(sInFile);
        try
        {
            IList<Dictionary<string, object>> bookmarks = SimpleBookmark.GetBookmark(pdfReader);

            for (int i = 0; i < bookmarks.Count; ++i)
            {
                IDictionary<string, object> BM = (IDictionary<string, object>)bookmarks[i];
                IDictionary<string, object> nextBM = i == bookmarks.Count - 1 ? null : bookmarks[i + 1];

                string startPage = BM["Page"].ToString().Split(' ')[0].ToString();
                string startPageNextBM = nextBM == null ? "" + (pdfReader.NumberOfPages + 1) : nextBM["Page"].ToString().Split(' ')[0].ToString();
                SplitByBookmark(pdfReader, int.Parse(startPage), int.Parse(startPageNextBM), bookmarks[i].Values.ToArray().GetValue(0).ToString() + ".pdf", fileName);

            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }

    private void SplitByBookmark(PdfReader reader, int pageFrom, int PageTo, string outPutName, string inPutFileName)
    {
        Document document = new Document();
        using (var fs = new FileStream(Path.GetDirectoryName(inPutFileName) + '\\' + outPutName, System.IO.FileMode.Create))
        {
            try
            {
                using (var writer = PdfWriter.GetInstance(document, fs))
                {
                    document.Open();
                    PdfContentByte cb = writer.DirectContent;
                    //holds pdf data
                    PdfImportedPage page;
                    if (pageFrom == PageTo && pageFrom == 1)
                    {
                        document.NewPage();
                        page = writer.GetImportedPage(reader, pageFrom);
                        cb.AddTemplate(page, 0, 0);
                        pageFrom++;
                        fs.Flush();
                        document.Close();
                        fs.Close();

                    }
                    else
                    {
                        while (pageFrom < PageTo)
                        {
                            document.NewPage();
                            page = writer.GetImportedPage(reader, pageFrom);
                            cb.AddTemplate(page, 0, 0);
                            pageFrom++;
                            fs.Flush();
                            document.Close();
                            fs.Close();
                        }
                    }
                }
                //PdfWriter writer = PdfWriter.GetInstance(document, fs);

            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }

You can install itextsharp from nuget and copy and paste this code in a c# app Call the SplitPDFByBookMark() method and pass the pdf filename. This code is going to search for you bookmarks and done!

查看更多
劫难
3楼-- · 2020-06-14 07:17

GroupDocs.Merger allows to split source document into several resultant documents. Document splitting can be performed in different ways by specifying page numbers array or start/end page numbers and setting different PageSplitOptions modes. Lets see how to split the document to several one-page documents (by exact page numbers):

string filePath = @"c:\sample.docx";
string filePathOut = @"c:\output\document_{0}.{1}";

PageSplitOptions splitOptions = new PageSplitOptions(filePathOut, new int[] { 3, 6, 8 });

using (Merger merger = new Merger(filePath))
{
     merger.Split(splitOptions);
} 

This code snippet will produce:
Document Name    Page Numbers
document_0             3
document_1             6
document_2             8

Learn more here.

Disclosure: I work as a developer evangelist at GroupDocs.

查看更多
老娘就宠你
4楼-- · 2020-06-14 07:21

This code is based on the PDFsharp library

http://www.pdfsharp.com/PDFsharp/

If you want to split by Book Mark then here is the code.

   public static void SplitPDFByBookMark(string fileName)
    {
        string sInFile = fileName;
        PdfReader pdfReader = new PdfReader(sInFile);
        try
        {
            IList<Dictionary<string, object>> bookmarks = SimpleBookmark.GetBookmark(pdfReader);

            for (int i = 0; i < bookmarks.Count; ++i)
            {
                IDictionary<string, object> BM = (IDictionary<string, object>)bookmarks[0];
                IDictionary<string, object> nextBM = i == bookmarks.Count - 1 ? null : bookmarks[i + 1];

                string startPage = BM["Page"].ToString().Split(' ')[0].ToString();
                string startPageNextBM = nextBM == null ? "" + (pdfReader.NumberOfPages + 1) : nextBM["Page"].ToString().Split(' ')[0].ToString();
                SplitByBookmark(pdfReader, int.Parse(startPage), int.Parse(startPageNextBM), bookmarks[i].Values.ToArray().GetValue(0).ToString() + ".pdf", fileName);

            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
    }
    private static void SplitByBookmark(PdfReader reader, int pageFrom, int PageTo, string outPutName, string inPutFileName)
    {
        Document document = new Document();
        FileStream fs = new System.IO.FileStream(System.IO.Path.GetDirectoryName(inPutFileName) + '\\' + outPutName, System.IO.FileMode.Create);

        try
        {

            PdfWriter writer = PdfWriter.GetInstance(document, fs);
            document.Open();
            PdfContentByte cb = writer.DirectContent;
            //holds pdf data
            PdfImportedPage page;
            if (pageFrom == PageTo && pageFrom == 1)
            {
                document.NewPage();
                page = writer.GetImportedPage(reader, pageFrom);
                cb.AddTemplate(page, 0, 0);
                pageFrom++;
                fs.Flush();
                document.Close();
                fs.Close();

            }
            else
            {
                while (pageFrom < PageTo)
                {
                    document.NewPage();
                    page = writer.GetImportedPage(reader, pageFrom);
                    cb.AddTemplate(page, 0, 0);
                    pageFrom++;
                    fs.Flush();
                    document.Close();
                    fs.Close();
                }
            }
        }
        catch (Exception ex)
        {
            throw ex;
        }
        finally
        {
            if (document.IsOpen())
                document.Close();
            if (fs != null)
                fs.Close();
        }

    }
查看更多
贼婆χ
5楼-- · 2020-06-14 07:23
public int ExtractPages(string sourcePdfPath, string DestinationFolder)
        {
            int p = 0;
            try
            {
                iTextSharp.text.Document document;
                iTextSharp.text.pdf.PdfReader reader = new iTextSharp.text.pdf.PdfReader(new iTextSharp.text.pdf.RandomAccessFileOrArray(sourcePdfPath), new ASCIIEncoding().GetBytes(""));
                if (!Directory.Exists(sourcePdfPath.ToLower().Replace(".pdf", "")))
                {
                    Directory.CreateDirectory(sourcePdfPath.ToLower().Replace(".pdf", ""));
                }
                else
                {
                    Directory.Delete(sourcePdfPath.ToLower().Replace(".pdf", ""), true);
                    Directory.CreateDirectory(sourcePdfPath.ToLower().Replace(".pdf", ""));
                }

                for (p = 1; p <= reader.NumberOfPages; p++)
                {
                    using (MemoryStream memoryStream = new MemoryStream())
                    {
                        document = new iTextSharp.text.Document();
                        iTextSharp.text.pdf.PdfWriter writer = iTextSharp.text.pdf.PdfWriter.GetInstance(document, memoryStream);
                        writer.SetPdfVersion(iTextSharp.text.pdf.PdfWriter.PDF_VERSION_1_2);
                        writer.CompressionLevel = iTextSharp.text.pdf.PdfStream.BEST_COMPRESSION;
                        writer.SetFullCompression();
                        document.SetPageSize(reader.GetPageSize(p));
                        document.NewPage();
                        document.Open();
                        document.AddDocListener(writer);
                        iTextSharp.text.pdf.PdfContentByte cb = writer.DirectContent;
                        iTextSharp.text.pdf.PdfImportedPage pageImport = writer.GetImportedPage(reader, p);
                        int rot = reader.GetPageRotation(p);
                        if (rot == 90 || rot == 270)
                        {
                            cb.AddTemplate(pageImport, 0, -1.0F, 1.0F, 0, 0, reader.GetPageSizeWithRotation(p).Height);
                        }
                        else
                        {
                            cb.AddTemplate(pageImport, 1.0F, 0, 0, 1.0F, 0, 0);
                        }
                        document.Close();
                        document.Dispose();
                        File.WriteAllBytes(DestinationFolder + "/" + p + ".pdf", memoryStream.ToArray());
                    }
                }
                reader.Close();
                reader.Dispose();
            }
            catch
            {
            }
            finally
            {
                GC.Collect();
            }
            return p - 1;

        }

call this function where ever you want and pass the source and destination folder path

查看更多
唯我独甜
6楼-- · 2020-06-14 07:25

I met the same question, you can use itextsharp component tools to split the document

public Split(String[] args)
    {
        if (args.Length != 4) 
        {
            Console.Error.WriteLine("This tools needs 4 parameters:\njava Split srcfile destfile1 destfile2 pagenumber");
        }
        else 
        {
            try 
            {
                int pagenumber = int.Parse(args[3]);

                // we create a reader for a certain document
                PdfReader reader = new PdfReader(args[0]);
                // we retrieve the total number of pages
                int n = reader.NumberOfPages;
                Console.WriteLine("There are " + n + " pages in the original file.");

                if (pagenumber < 2 || pagenumber > n) 
                {
                    throw new DocumentException("You can't split this document at page " + pagenumber + "; there is no such page.");
                }

                // step 1: creation of a document-object
                Document document1 = new Document(reader.GetPageSizeWithRotation(1));
                Document document2 = new Document(reader.GetPageSizeWithRotation(pagenumber));
                // step 2: we create a writer that listens to the document
                PdfWriter writer1 = PdfWriter.GetInstance(document1, new FileStream(args[1], FileMode.Create));
                PdfWriter writer2 = PdfWriter.GetInstance(document2, new FileStream(args[2], FileMode.Create));
                // step 3: we open the document
                document1.Open();
                PdfContentByte cb1 = writer1.DirectContent;
                document2.Open();
                PdfContentByte cb2 = writer2.DirectContent;
                PdfImportedPage page;
                int rotation;
                int i = 0;
                // step 4: we add content
                while (i < pagenumber - 1) 
                {
                    i++;
                    document1.SetPageSize(reader.GetPageSizeWithRotation(i));
                    document1.NewPage();
                    page = writer1.GetImportedPage(reader, i);
                    rotation = reader.GetPageRotation(i);
                    if (rotation == 90 || rotation == 270) 
                    {
                        cb1.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                    }
                    else 
                    {
                        cb1.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                    }
                }
                while (i < n) 
                {
                    i++;
                    document2.SetPageSize(reader.GetPageSizeWithRotation(i));
                    document2.NewPage();
                    page = writer2.GetImportedPage(reader, i);
                    rotation = reader.GetPageRotation(i);
                    if (rotation == 90 || rotation == 270) 
                    {
                        cb2.AddTemplate(page, 0, -1f, 1f, 0, 0, reader.GetPageSizeWithRotation(i).Height);
                    }
                    else 
                    {
                        cb2.AddTemplate(page, 1f, 0, 0, 1f, 0, 0);
                    }
                    Console.WriteLine("Processed page " + i);
                }
                // step 5: we close the document
                document1.Close();
                document2.Close();
            }
            catch(Exception e) 
            {
                Console.Error.WriteLine(e.Message);
                Console.Error.WriteLine(e.StackTrace);
            }
        }

    }
查看更多
神经病院院长
7楼-- · 2020-06-14 07:27

You can use a PDF library like PDFSharp, read the file, iterate through each of the pages, add them to a new PDF document and save them on the filesystem. You can then also delete or keep the original.

It's quite a bit of code, but very simple and these samples should get you started.

http://www.pdfsharp.net/wiki/Default.aspx?Page=ConcatenateDocuments-sample&NS=&AspxAutoDetectCookieSupport=1

查看更多
登录 后发表回答